【发布时间】: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 询问他们