简体   繁体   English

在Ocaml中进行列表递归

[英]List Recursion in Ocaml

This is what I want to achive, to return to a list with values that are below the given value with recursion : 这是我要达到的目的,并通过递归返回到一个值低于给定值的列表:

# 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]

Here is what I wrote so far, and it does not appear to return anything. 这是我到目前为止所写的内容,似乎没有返回任何内容。

let rec list_below thresh lst = 
 if List.hd lst > thresh then [] else
  List.hd lst :: list_below thresh (List.tl lst);;
;;

Could you show me what is wrong with my code? 您能告诉我我的代码有什么问题吗?

The problem should be what Jeffrey has pointed out for you. 问题应该是杰弗里为您指出的。

Your questions says you want to implement list_below , but your code shows list_above . 您的问题表明您想实现list_below ,但是您的代码显示为list_above I'll stick to list_below here. 我会在下面坚持到list_below

Recursive functions in Ocaml can be made quite intuitively if you use pattern matching . 如果使用模式匹配,则可以非常直观地实现Ocaml中的递归函数 For example, the below code should work : 例如,下面的代码应该工作:

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;;

If the first value is above the threshhold your code always returns an empty list. 如果第一个值高于阈值,则您的代码始终返回一个空列表。 That can't be right. 那是不对的。 It is inconsistent with your first example, for one thing. 一方面,它与您的第一个示例不一致。

You could try using List.filter . 您可以尝试使用List.filter Since you want to get a list of values that are less than the supplied value, then filter should do what you want. 由于要获取小于提供的值的值列表,因此filter可以执行所需的操作。

Here's the documentation for 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.

What you need is to provide a predicate p. 您需要提供一个谓词p。 A predicate is a function that takes an element and returns a boolean. 谓词是一个接受元素并返回布尔值的函数。 Filter will take this predicate and apply to each value in the list. 筛选器将使用此谓词并将其应用于列表中的每个值。 If the predicate returns true for that element, the element will be added to the resulting list. 如果谓词对该元素返回true,则该元素将添加到结果列表中。

So in your case, list_below should be 所以在你的情况下, list_below应该是

let list_below thresh lst =
    List.filter (fun elem -> elem < thresh) lst

More more operations on list, check out this chapter in Real World OCaml. 列表中还有更多操作,请查看Real World OCaml中的本章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM