为什么会这样(Ocaml)
Why is this happening (Ocaml)
在 Ocaml 语言中,目标是合并(追加)两个列表,同时删除重复项。
let rec find_dup a lst =
match lst with
| [] -> false
| hd::tl -> if (hd == a) then true else find_dup a tl;;
let rec app lst2 lst1 =
match lst1 with
| [] -> lst2
| hd::tl -> if (find_dup hd lst2) then (app tl lst2)
else hd::app tl lst2
;;
我有这样的代码,但是当测试用例是
app [4;5;6;7] [1;2;3;4] 答案应该是 [1;2;3;4;5;6;7]
但我不断收到
- : 整数列表 = [1; 2; 5; 3; 6; 4; 7]
这是怎么回事?
您正在为每个递归调用切换列表。
查看函数定义的参数顺序:
let rec app lst2 lst1
然后递归函数调用:
app tl lst2
此外,只是吹毛求疵,find_dup
已经存在于标准库中。它被称为 List.mem
。
在 Ocaml 语言中,目标是合并(追加)两个列表,同时删除重复项。
let rec find_dup a lst =
match lst with
| [] -> false
| hd::tl -> if (hd == a) then true else find_dup a tl;;
let rec app lst2 lst1 =
match lst1 with
| [] -> lst2
| hd::tl -> if (find_dup hd lst2) then (app tl lst2)
else hd::app tl lst2
;;
我有这样的代码,但是当测试用例是 app [4;5;6;7] [1;2;3;4] 答案应该是 [1;2;3;4;5;6;7] 但我不断收到
- : 整数列表 = [1; 2; 5; 3; 6; 4; 7]
这是怎么回事?
您正在为每个递归调用切换列表。
查看函数定义的参数顺序:
let rec app lst2 lst1
然后递归函数调用:
app tl lst2
此外,只是吹毛求疵,find_dup
已经存在于标准库中。它被称为 List.mem
。