Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match one item in List of tuples

Tags:

list

ocaml

I have a List of tuples of the form (string, int). I'm trying to search through the list and return the tuple whose string component matches the parameter, as in: let find_tuple string_name tuples_list =

How can I do this? I can't quite wrap my head around it. Is there a way to use matching syntax like (string, _) ->...?

like image 834
yavoh Avatar asked Dec 17 '10 17:12

yavoh


Video Answer


2 Answers

You can achieve this as following

let rec find_tuple string_name tuples_list =
       match tuples_list with
            [] -> raise Not_found
            |(s, i)::tl -> if s = string_name then (s, i) 
                                  else find_tuple string_name tl

or simply

List.find (fun s -> fst s = string_name) tuples_list
like image 174
0xFF Avatar answered Oct 20 '22 12:10

0xFF


Yes, you do use matching syntax like that, but will need match guards (or you can use if then else). The List module has a function called find that will return the first element that matches a predicate. It also has the function filter (and find_all - same function) that returns a list of all the elements that match the predicate. For example:

let predicate string_name tuple = match tuple with (s, _) when s = string_name -> true
  | _ false

try
  let x = List.find (predicate "query") tuples_list in
    ...
  with Not_found -> ...

EDIT: a better predicate:

let predicate string_name (s, _) = s = string_name

However the better solution is to use List.assoc which works on lists of tuples, and considers the tuples to be key-value pairs:

try
  let x = List.assoc "query" tuples_list in ...
with Not_found -> ...

Although the return value of List.assoc is the second element of the tuple (an int in your case). If you want the value of the tuple, either recreate it, or use the first approach.

like image 30
Niki Yoshiuchi Avatar answered Oct 20 '22 11:10

Niki Yoshiuchi