【问题标题】:OCaml function to return a list of tuples whose last element matches a predicateOCaml 函数返回一个元组列表,其最后一个元素与谓词匹配
【发布时间】:2015-03-03 23:57:06
【问题描述】:

我正在尝试在 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

但这只会返回与谓词匹配的第一个元组。我要改变什么让它返回所有匹配的元组?

【问题讨论】:

    标签: ocaml


    【解决方案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 通常称为累加器变量。

    【讨论】:

      【解决方案2】:

      想想then之后的情况。为什么你会如此确定你只需要在那个时候向l1 添加一个额外的元组。也许还有一些在尾巴。

      【讨论】:

        【解决方案3】:
        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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-01-06
          • 1970-01-01
          • 2012-01-21
          • 2016-03-06
          • 1970-01-01
          • 2021-03-11
          相关资源
          最近更新 更多