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, _) ->...
?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With