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?
推荐答案
问题应该是 Jeffrey 为您指出的问题.
The problem should be what Jeffrey has pointed out for you.
您的问题表明您想要实现 list_below
,但您的代码显示了 list_above
.我会在这里使用 list_below
.
Your questions says you want to implement list_below
, but your code shows list_above
. I'll stick to list_below
here.
递归函数模式匹配.例如,下面的代码应该可以工作:
Recursive functions in Ocaml can be made quite intuitively if you use pattern matching. 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;;
这篇关于Ocaml 中的列表递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!