Reputation: 63
the function nth must work like this :
# 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
I wrote this function named nth like this :
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
So I typed nth [1;2;3;4;5] 3
and the expected output was 4 but the console said "list is too short"
My expected algorithm is this : 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
What is wrong with my code?
Upvotes: 1
Views: 811
Reputation: 66823
This is a precedence problem. The expression nth tl n-1
is parsed like this: (nth tl n) - 1
. You need parentheses like this: nth tl (n - 1)
.
If you try your current code with a list of strings (say), you'll get a possibly more helpful error message from the toplevel.
Other than this one problem your code looks excellent btw.
Upvotes: 3