用 OCaml 重写 Scheme 代码?
Rewrite the Scheme code in OCaml?
(define unique
(lambda (L)
(cond ((null? L) L)
((null? (cdr L)) L)
((eqv? (car L) (car (cdr L))) (unique (cdr L)))
(else (cons (car L) (unique (cdr L))))))
以上代码(#racket 语言)从列表中找到唯一元素。我想将这个球拍代码翻译成 OCaml。
到目前为止我已经
let rec unique func lis =
match lis with
| [] -> []
| (h::lis') -> if lis = []
then x (* There is only one item in the list which was captured by head and the tail is null *)
此代码不正确。它遗漏了我坚持的 else 语句。
看方案代码有四种情况。
((null? L) L)
,很好地对应于您的 OCaml 代码中的 | [] -> []
。
((null? (cdr L)) L)
检查列表是否只有一个元素,它的 OCaml 代码是 | [x] -> [x]
如果它有两个或更多元素,你检查第一个和第二个元素是否相同。
如果是,答案是(unique (cdr L))
;
如果不是,则为 (cons (car L) (unique (cdr L)))
.
您可以使用模式匹配来获取前两个元素,如下所示:| first::second::rest -> if ...
用 OCaml 翻译你的算法给我:
let rec unique l = match l with
| [] -> []
| [x] -> [x]
| x :: y :: tl -> if x = y then y :: unique tl else x :: unique ( y :: tl);;
(define unique
(lambda (L)
(cond ((null? L) L)
((null? (cdr L)) L)
((eqv? (car L) (car (cdr L))) (unique (cdr L)))
(else (cons (car L) (unique (cdr L))))))
以上代码(#racket 语言)从列表中找到唯一元素。我想将这个球拍代码翻译成 OCaml。 到目前为止我已经
let rec unique func lis =
match lis with
| [] -> []
| (h::lis') -> if lis = []
then x (* There is only one item in the list which was captured by head and the tail is null *)
此代码不正确。它遗漏了我坚持的 else 语句。
看方案代码有四种情况。
((null? L) L)
,很好地对应于您的 OCaml 代码中的 | [] -> []
。
((null? (cdr L)) L)
检查列表是否只有一个元素,它的 OCaml 代码是 | [x] -> [x]
如果它有两个或更多元素,你检查第一个和第二个元素是否相同。
如果是,答案是(unique (cdr L))
;
如果不是,则为 (cons (car L) (unique (cdr L)))
.
您可以使用模式匹配来获取前两个元素,如下所示:| first::second::rest -> if ...
用 OCaml 翻译你的算法给我:
let rec unique l = match l with
| [] -> []
| [x] -> [x]
| x :: y :: tl -> if x = y then y :: unique tl else x :: unique ( y :: tl);;