[英]Ocaml: Recursion: intersection
function name: intersection: takes 2 lists and returns list of all elements that appear in both 函数名称:交集:接受2个列表并返回同时出现在两个元素中的所有元素的列表
ie: [1; 即:[1; 2;
2; 2;
2; 3;
3; 4;
4; 4;
4; 3] [2;
3] [2; 3] -> [2;
3]-> [2; 2;
2; 3;
3; 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
There is a problem with this code, but I'm not sure how to fix it - The code will run through and get [2; 这段代码有问题,但是我不确定如何解决-该代码将贯穿并得到[2; 2] because it keeps comparing to 2, the first element in l2, but I want l1 to also compare with tl2, does anyone have any suggestions?
2]因为它一直与2中的第一个元素2进行比较,但是我希望l1也与tl2比较,有人对它有什么建议吗?
Should I add another match [], [] -> to clarify base case at the beginning?
how do you refer to the first element in the other list?
您如何引用其他列表中的第一个元素?
Use another match
statement: 使用另一个
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
You can also simplify this by omitting the begin
/ end
parenthesis that are unnecessary in this case, and by matching upon a tuple right away: 您还可以通过省略在这种情况下不必要的
begin
/ end
括号并立即匹配一个元组来简化此操作:
let rec intersection (l1: int list) (l2: int list) : int list = match l1, l2 with
| [], _ -> []
| hd1::tl1, [] -> …
| hd1::tl1, hd2::tl2 -> …
(Disclaimer: I ignored the question whether looking at the two first elements in the same function is useful for implementing intersection
at all) (免责声明:我忽略了一个问题,即查看同一函数中的前两个元素是否对实现
intersection
完全有用)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.