OCaml函数返回最后一个元素与谓词匹配的元组列表

时间:2015-03-03 15:35:35

标签: ocaml

我试图在OCaml中编写一个函数,它接受一个谓词,一个元组列表和一个空列表,并返回原始列表中最后一个成员满足谓词的元组列表。

到目前为止我所拥有的是:

let rec find_tuples p l l1 = 
match l with
| [] -> []
| (n,s,f) :: t -> if p f then ((n,s,f) :: l1) else find_tuples p t l1

但这只返回与谓词匹配的第一个元组。我该怎么做才能让它返回所有匹配的元组?

3 个答案:

答案 0 :(得分:1)

即使您找到了第一个匹配的元组,也需要继续按照列表进行操作。事实上,我们可以同意你应该遍历整个列表,直到你到达[]

let rec find_tuples p l l1 =
match l with
| [] -> failwith "we're here after a traversal or l1 is empty"
| ( (_,_,f) as e) :: t ->
  if p f
  then find_tuples p t (e::l1)
  else find_tuples p t l1

当然,我离开你的那次失败并不是正确的答案。如果没有进行遍历,我们需要[],如果有递归调用,我们需要l1。等等,l1适用于这两种情况! 因此failwith应替换为l1

在这些情况下,l1通常称为累加器变量。

答案 1 :(得分:0)

考虑then之后的情况。为什么你会这么确定你只需要在l1添加一个额外的元组。也许还有更多的东西。

答案 2 :(得分:0)

let rec find_tuples p l l1 = 
match l with
| [] -> []
| (n,s,f) :: t -> if p f then find_tuples p t ((n,s,f) :: l1) else find_tuples p t l1

当条件成立时,不要忘记回忆l尾部的功能。

编辑:另一个解决方案是使用List.filter

let find_tuples p l = List.filter (fun (n,s,f) -> p f) l
相关问题