【问题标题】:OCaml: Removing consecutive duplicates from a list without recursionOCaml:从列表中删除连续重复项而不递归
【发布时间】:2016-01-12 00:31:56
【问题描述】:

我应该从int list 中删除连续的重复项,而不使用递归,并且只使用List.foldmapfilterfold_leftfold_right

我几乎明白了,但我的代码的问题是它检查每个元素是否等于第二个元素,而不是下一个元素。

例如,如果let z = int list [3;1;4;5;5;1;1] 我的代码将返回[3;4;5] 而不是[3;1;4;5;1]。我不确定如何更改它,因此filter 使用动态更改的列表参数,而不仅仅是原始参数(因此它不会每次都将每个元素与第二个元素(在这种情况下为 1)进行比较):

let dupe (ls: int list) : int list =
    List.filter (fun x -> if List.length ls = 0 then true else if x = List.hd (List.tl xs) then false else true) ls

【问题讨论】:

    标签: list recursion module duplicates ocaml


    【解决方案1】:

    List.filter 的类型是这样的:

    # List.filter;;
    - : ('a -> bool) -> 'a list -> 'a list = <fun>
    

    值得注意的是,过滤器函数一次只能看到列表中的一个元素。您需要查看两个连续的元素来决定要做什么,所以我会说List.filter 不会做这项工作。

    你将不得不使用map 或其中一个折叠,我会说。通过类似的推理,您可以找出哪个(或哪些)有用。

    (我认为这是作业应该说明的那种推理。所以我将把它留在那里。)

    【讨论】:

      【解决方案2】:

      没有录音

       let remove = function
              []    -> []
            | x::tl -> 
               let (_,lxRes)=
                 List.fold_left (
                  fun (xPrec,lxRes) xCour ->
                   if xPrec=xCour then
                     (xCour,lxRes)
                   else
                     (xCour,lxRes@[xCour])
                 ) (x+1,[]) (x::tl)
                in
                lxRes
      

      测试:

      # remove  [3;1;4;5;5;1;1];;
      - : int list = [3; 1; 4; 5; 1]
      # remove [1;1];;
      - : int list = [1]
      # remove [1;1;1;1;2;2;3;4;5;5];;
      - : int list = [1; 2; 3; 4; 5]
      

      带有rec(仅供参考)

      let rec remove =
      function
        | []       -> []
        | x::[]    -> x::[]
        | x::y::tl ->
           if x=y then remove (y::tl)
           else x::remove (y::tl)
      

      【讨论】:

      • 嗯。 fold_left 是递归的。我会使用引用作为可变变量。那么您的代码非常不合时宜,请参阅一些样式指南。那么你通常不仅会给出家庭作业的解决方案,还会给出提示或半途而废的解决方案。
      猜你喜欢
      • 2018-09-30
      • 2021-07-01
      • 1970-01-01
      • 2014-04-19
      • 2021-05-12
      • 2018-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多