在Ocaml中进行列表递归

时间:2018-09-11 02:15:48

标签: recursion 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);;
;;

您能告诉我我的代码有什么问题吗?

3 个答案:

答案 0 :(得分:1)

问题应该是杰弗里为您指出的。

您的问题说您想实现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;;

答案 1 :(得分:0)

如果第一个值高于阈值,则您的代码始终返回一个空列表。那是不对的。一方面,它与您的第一个示例不一致。

答案 2 :(得分:0)

您可以尝试使用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

相关问题