(Ocaml) 如何仅使用 List.hd、List.tl 和 List.length 从列表中删除所有其他元素
(Ocaml) How to remove every other element from a list only using List.hd, List.tl, and List.length
我有一个 Ocaml 问题需要帮助,因为我真的无法解决。我对编码并不陌生,但 Ocaml 让我重新考虑我的 career/academic 选择。
编写一个函数,从列表中删除所有其他元素。 ['d'; 'o'; 'u'; 'c'; 'h'; 'e'; 'c'; 'a'; 'n'; 'o'; 'e'] -> ['d'; 'u'; 'h'; 'c'; 'n'; 'e']
必须是递归的方法,只能用List.hd、List.tl、List.length,其他的都不行。
这是一个删除列表最后一个元素的函数示例:显然应该以类似的方式完成:
let rec rm_last_element l =
if List.tl l = []
then []
else List.hd l :: remove_last(List.tl l);;
哪位好心人能帮我解决一下吗?不一定是代码,但只要向我清楚地解释你会怎么做?我知道正确的做法是给我提示,让我自己解决,但到目前为止没有结果。
非常感谢
您可以使用这样的模式匹配:
match l with
| x1 :: x2 :: tale -> (* remove x2 : x1 is the first element x2 the second
and tale is the rest of the list *)
| _ -> (* else don't change the list*)
有关路径匹配的更多信息(与 List.hd 和 List.tale 隐式相同,请参阅 this link
想想 OCaml 中的列表是什么样的:
[1 ; 4; 6; 3; 8; 9; 10]
可以写成1 :: 4 :: 6 :: 3 :: 8 :: 9 :: 10 :: []
.
我们可以对列表进行模式匹配。 (扩展了 Butanium 展示的内容。)
match [1 ; 4; 6; 3; 8; 9; 10] with
(* The case of an empty list *)
| [] ->
(* The case of a list with a single element,
where the single element has the value 1. *)
| elt :: [] ->
(* The case of a list with at least two elements,
where elt1 is 1, and elt2 is 4 and
rest is [6; 3; 8; 9; 10] *)
| elt1 :: elt2 :: rest ->
如果您想删除所有其他元素,每个案例需要什么 return?如果我们在 [6; 3; 8; 9; 10]
上进行相同的匹配,我们会得到什么?在这种情况下,elt1
、elt2
和 rest
会是什么?
我有一个 Ocaml 问题需要帮助,因为我真的无法解决。我对编码并不陌生,但 Ocaml 让我重新考虑我的 career/academic 选择。
编写一个函数,从列表中删除所有其他元素。 ['d'; 'o'; 'u'; 'c'; 'h'; 'e'; 'c'; 'a'; 'n'; 'o'; 'e'] -> ['d'; 'u'; 'h'; 'c'; 'n'; 'e']
必须是递归的方法,只能用List.hd、List.tl、List.length,其他的都不行。
这是一个删除列表最后一个元素的函数示例:显然应该以类似的方式完成:
let rec rm_last_element l =
if List.tl l = []
then []
else List.hd l :: remove_last(List.tl l);;
哪位好心人能帮我解决一下吗?不一定是代码,但只要向我清楚地解释你会怎么做?我知道正确的做法是给我提示,让我自己解决,但到目前为止没有结果。
非常感谢
您可以使用这样的模式匹配:
match l with
| x1 :: x2 :: tale -> (* remove x2 : x1 is the first element x2 the second
and tale is the rest of the list *)
| _ -> (* else don't change the list*)
有关路径匹配的更多信息(与 List.hd 和 List.tale 隐式相同,请参阅 this link
想想 OCaml 中的列表是什么样的:
[1 ; 4; 6; 3; 8; 9; 10]
可以写成1 :: 4 :: 6 :: 3 :: 8 :: 9 :: 10 :: []
.
我们可以对列表进行模式匹配。 (扩展了 Butanium 展示的内容。)
match [1 ; 4; 6; 3; 8; 9; 10] with
(* The case of an empty list *)
| [] ->
(* The case of a list with a single element,
where the single element has the value 1. *)
| elt :: [] ->
(* The case of a list with at least two elements,
where elt1 is 1, and elt2 is 4 and
rest is [6; 3; 8; 9; 10] *)
| elt1 :: elt2 :: rest ->
如果您想删除所有其他元素,每个案例需要什么 return?如果我们在 [6; 3; 8; 9; 10]
上进行相同的匹配,我们会得到什么?在这种情况下,elt1
、elt2
和 rest
会是什么?