匹配元组列表中的一项
问题描述:
我有一个格式为(string, int)
的元组列表.我正在尝试搜索列表并返回其字符串成分与参数匹配的元组,如:let find_tuple string_name tuples_list =
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 =
我该怎么做?我不能完全包住它.有没有办法使用像(string, _) ->...
这样的匹配语法?
How can I do this? I can't quite wrap my head around it. Is there a way to use matching syntax like (string, _) ->...
?
答
您可以按以下步骤实现
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
或者简单地
List.find (fun s -> fst s = string_name) tuples_list