Match one item in List of tuples

非 Y 不嫁゛ 提交于 2020-01-03 08:27:28

问题


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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/4473163/match-one-item-in-list-of-tuples

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!