OCaml 函数 return 一个元组列表,其最后一个元素与谓词匹配

OCaml function to return a list of tuples whose last element matches a predicate

我正在尝试在 OCaml 中编写一个函数,它接受一个谓词、一个元组列表和一个空列表,returns 是原始列表中最后一个成员满足谓词的元组列表。

我目前拥有的是:

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

但这只是 return 匹配谓词的第一个元组。我要更改什么才能使其成为 return 所有匹配的元组?

想想then之后的情况。为什么您会如此确定此时只需要向 l1 添加一个额外的元组。可能尾部还有一些。

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

即使找到第一个匹配的元组,您也需要继续浏览列表。事实上,我们同意您应该遍历整个列表,直到到达 []:

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

当然,failwith I left you 不是正确答案。如果没有完成遍历,我们需要它是 [],如果有递归调用,我们需要它是 l1。等等,l1 在这两种情况下都有效!
所以 failwith 应该替换为 l1.

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