[英]List Recursion in Ocaml
这是我要达到的目的,并通过递归返回到一个值低于给定值的列表:
# list_below 3 [7; 1; 0; 3];;
- : int list = [1; 0]
# list_below 1 [-7; 1; 0; 3];;
- : int list = [-7; 0]
# list_below 9.0 [4.2; 3.6; 5.0; 12.8];;
- : float list = [4.2; 3.6; 5.0]
这是我到目前为止所写的内容,似乎没有返回任何内容。
let rec list_below thresh lst =
if List.hd lst > thresh then [] else
List.hd lst :: list_below thresh (List.tl lst);;
;;
您能告诉我我的代码有什么问题吗?
问题应该是杰弗里为您指出的。
您的问题表明您想实现list_below
,但是您的代码显示为list_above
。 我会在下面坚持到list_below
。
如果使用模式匹配,则可以非常直观地实现Ocaml中的递归函数 。 例如,下面的代码应该工作:
let rec list_below thresh lst =
match lst with
| [] -> []
| hd :: tl -> if hd < thresh then hd :: (list_below thresh tl)
else list_below thresh tl;;
如果第一个值高于阈值,则您的代码始终返回一个空列表。 那是不对的。 一方面,它与您的第一个示例不一致。
您可以尝试使用List.filter
。 由于要获取小于提供的值的值列表,因此filter可以执行所需的操作。
这是过滤器的文档:
val filter : ('a -> bool) -> 'a list -> 'a list
filter p l returns all the elements of the list l that satisfy the predicate p. The order of the elements in the input list is preserved.
您需要提供一个谓词p。 谓词是一个接受元素并返回布尔值的函数。 筛选器将使用此谓词并将其应用于列表中的每个值。 如果谓词对该元素返回true,则该元素将添加到结果列表中。
所以在你的情况下, list_below
应该是
let list_below thresh lst =
List.filter (fun elem -> elem < thresh) lst
列表中还有更多操作,请查看Real World OCaml中的本章 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.