Take the 2-minute tour ×

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, _) ->...?

share|improve this question

2 Answers 2

up vote 5 down vote accepted

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
share|improve this answer
You can use the as keyword to simplify things a little bit: | ((s, i) as h)::tl -> if ... then h else ... Also, didn't know about the fst function, thanks for pointing it out! –  Niki Yoshiuchi Dec 17 '10 at 17:49
The second option can also be written as List.find (fun (string, _) -> string = string_name) tuples_list, which has the (string, _) the OP wanted. –  sepp2k Dec 17 '10 at 17:53
Thanks! With a let rec it worked perfectly. –  yavoh Dec 17 '10 at 18:00

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

  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:

  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.

share|improve this answer

Your Answer


