2010-12-17 86 views
8

我有一个形式为(string, int)的元组列表。我试图通过列表搜索并返回其字符串组件与参数匹配的元组,如下所示:let find_tuple string_name tuples_list =匹配元组列表中的一个项目

我该怎么做?我无法把头绕在里面。有没有一种方法可以使用像(string, _) ->...这样的匹配语法?

回答

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 

或者干脆

List.find (fun s -> fst s = string_name) tuples_list 
+0

您可以使用'as'关键字来简化一些事情:'| ((s,i)as h):: tl - > if ... then h else ...'另外,不知道'fst'函数,谢谢指出! – 2010-12-17 17:49:49

+1

第二个选项也可以写成'List.find(fun(string,_) - > string = string_name)tuples_list',它具有OP想要的'(string,_)'。 – sepp2k 2010-12-17 17:53:29

+0

谢谢!有一个'让rec'它完美的工作。 – yavoh 2010-12-17 18:00:00

1

是的,你确实使用匹配语法类似,但需要匹配后卫(或者你可以,如果再使用别的) 。 List模块具有一个名为find的函数,该函数将返回与谓词匹配的第一个元素。它还具有函数filter(和find_all - 相同的函数),它返回与谓词匹配的所有元素的列表。例如:

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 -> ... 

编辑:更好的谓词:

let predicate string_name (s, _) = s = string_name 

然而,更好的解决方案是使用List.assoc其上的元组的列表的工作,并认为元组是键值对:

try 
    let x = List.assoc "query" tuples_list in ... 
with Not_found -> ... 

虽然List.assoc返回值是元组的(在你的情况下的int)第二元件。如果你想要元组的值,可以重新创建它,或者使用第一种方法。

相关问题