函数nth必须像这样工作:
# nth [1;2;3;4;5] 0;;
- : int = 1
# nth [1;2;3;4;5] 1;;
- : int = 2
# nth [1;2;3;4;5] 2;;
- : int = 3
# nth [1;2;3;4;5] 3;;
- : int = 4
我这样写了一个名为nth的函数:
let rec nth l n =
match l with
|[] -> raise (Failure "list is too short")
|hd::tl ->
if n > 0 then nth tl n-1 else hd
因此,我输入nth [1;2;3;4;5] 3
了预期的输出为4,但控制台说“列表太短”
我期望的算法是:nth [1; 2; 3; 4; 5] 3
1::[2;3;4;5] 3 > 0 is true, so nth [2;3;4;5] 2 is called.
2::[3;4;5] 2 > 0 is true, so nth [3;4;5] 1 is called.
3::[4,5] 1 > 0 is true, so nth [4;5] 0 is called
4::[5] 0 > 0 is false, so return 4
so nth [1;2;3;4;5] 3 = 4
我的代码有什么问题?
这是一个优先问题。表达nth tl n-1
被解析这样的:(nth tl n) - 1
。您需要这样的括号:nth tl (n - 1)
。
如果使用字符串列表(例如)尝试当前代码,则可能会从顶层获得更有用的错误消息。
除此之外,您的代码看起来还不错。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句