匹配元组列表中的一个项目

yav*_*voh 8 ocaml list

我有一个表格的元组列表(string, int).我正在尝试搜索列表并返回其字符串组件与参数匹配的元组,如:let find_tuple string_name tuples_list =

我怎样才能做到这一点?我无法完全绕过它.有没有办法使用匹配的语法(string, _) ->...

0xF*_*xFF 7

您可以通过以下方式实现此目的

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
Run Code Online (Sandbox Code Playgroud)

或者干脆

List.find (fun s -> fst s = string_name) tuples_list
Run Code Online (Sandbox Code Playgroud)