这是我想要实现的,通过递归返回到具有低于给定值的值的列表:
# 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
。
如果使用pattern matching,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
。由于您希望获得小于提供值的值列表,因此过滤器应该执行您想要的操作。
这是过滤器的文档:
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中的chapter。