【问题标题】:Ocaml: Recursion: intersectionOcaml:递归:交集
【发布时间】:2017-03-08 03:22:26
【问题描述】:

函数名:intersection:接受 2 个列表并返回出现在两者中的所有元素的列表

即:[1; 2; 2; 3; 4; 4; 3] [2; 3] -> [2; 2; 3; 3]

let rec intersection (l1: int list) (l2: int list) : int list = 
    begin match l1, l2 with
      | hd :: tl, hd2 :: tl2 -> if hd = hd2 then hd :: intersection tl l2
                                            else intersection tl l2
      | _ -> []
    end

这段代码有问题,但我不知道如何修复它 - 代码将运行并得到 [2; 2] 因为它一直在与 l2 中的第一个元素 2 进行比较,但我希望 l1 也与 tl2 进行比较,有人有什么建议吗?

 Should I add another match [], [] -> to clarify base case at the beginning?

【问题讨论】:

  • 会怎么写呢?您面临哪些问题?请向我们展示您的尝试或告诉我们您的方法。 StackOverflow 可以为您的家庭作业提供帮助,但我们不会为您解决。
  • 有没有更有效的方法来实现这段代码?每隔一个:每个第二个元素,即:[1; 2; 3; 4; 5] -> [1; 3; 5] let rec every_other (l: int list) : int list = begin match l with | [] -> [] | hd :: tl -> hd :: every_other tl end
  • 还是这个? let rec all_even (l: int list): bool = begin match l with | []->真| hd :: tl -> (hd mod 2 = 0) && all_event tl end
  • 这些是完全独立的问题,应该按原样发布,而不是作为 cmets。但是,鉴于他们似乎在询问工作代码以及如何改进它,无论如何他们在 StackOverflow 上都是题外话,你最好在 Code Review 询问他们

标签: recursion ocaml


【解决方案1】:

你如何引用另一个列表中的第一个元素?

使用另一个match 声明:

let rec intersection (l1: int list) (l2: int list) : int list = 
    begin match l2 with
      | []         -> []
      | hd2 :: tl2 -> begin match l1 with
                        | []         -> …
                        | hd1 :: tl1 -> …
                      end
    end

您还可以通过省略在这种情况下不必要的 begin/end 括号并立即匹配元组来简化此操作:

let rec intersection (l1: int list) (l2: int list) : int list = match l1, l2 with
  | [],       _        -> []
  | hd1::tl1, []       -> …
  | hd1::tl1, hd2::tl2 -> …

(免责声明:我忽略了在同一个函数中查看前两个元素是否对实现intersection 有用的问题)

【讨论】:

  • 你能用 | 开始匹配 l1、l2 [], [] -> | hd1 :: tl1, hd2::tl2 还是效率更低?
  • 或者我可以写一个像“contains”这样的辅助函数,然后如果 contains 为真,那么 hd1::intersection tl
  • 是的,您可以这样做,但不要忘记涵盖所有四种空/非空列表的情况
  • 是的,contains 辅助函数对于intersection 来说听起来是个绝妙的主意
猜你喜欢
  • 2012-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-09
  • 2014-12-09
  • 2013-06-01
相关资源
最近更新 更多