All*_*ang 3 ocaml functional-programming list
我正在与OCaml合作开发一个项目,并且我对数组有一些问题,我不确定.我不被允许使用List模块,所以请给我一些关于我的作品的想法或建议.
首先,我已经实现了一个功能'a list -> 'a list叫做uniq数组中的返回uniq的元素的列表,例如 uniq [5;6;5;4] => [6;5;4]
这是我的实现:
let rec uniq x =
let rec uniq_help l n =
match l with
[] -> []
| h :: t -> uniq_help t, n if (n = h) else (h :: (uniq_help(t, n)))
match x with
[] -> []
| h::t -> uniq_help t, h
;;
Run Code Online (Sandbox Code Playgroud)
我确信这是一个正确的实施,有人可以给我一些建议或正确吗?
由于各种原因,您的函数在语法上是不正确的:
uniq_help需要两个元素,所以你必须使用uniq_help t n,而不是等等来调用它uniq_help(t, n).if/else表达应具有的形式if cond then expr1 else expr2.uniq_help在本地使用uniq,您需要一个in关键字.修复语法错误后,您的函数如下所示:
let rec uniq x =
let rec uniq_help l n =
match l with
| [] -> []
| h :: t -> if n = h then uniq_help t n else h::(uniq_help t n) in
match x with
| [] -> []
| h::t -> uniq_help t h
Run Code Online (Sandbox Code Playgroud)
但是,为了确保列表中的每个元素都是唯一的,您必须检查其所有元素的唯一性.一个快速解决方案可能是:
let rec uniq x =
(* uniq_help is the same as above *)
match x with
| [] -> []
| h::t -> h::(uniq_help (uniq t) h)
Run Code Online (Sandbox Code Playgroud)