[英]Ocaml: Recursion: 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]因為它一直與2中的第一個元素2進行比較,但是我希望l1也與tl2比較,有人對它有什么建議嗎?
Should I add another match [], [] -> to clarify base case at the beginning?
您如何引用其他列表中的第一個元素?
使用另一個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
完全有用)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.