I’m trying to write a function that accepts an int n and returns a list that runs down from n to 0.
This is what I have
let rec downFrom n =
let m = n+1 in
if m = 0 then
[]
else
(m-1) :: downFrom (m - 1);;
The function compiles ok but when I test it with any int it gives me the error
Stack overflow during evaluation (looping recursion?).
I know it’s the local varible that gets in the way but I don’t know another way to declare it. Thank you!!!
First, the real thing wrong with your program is that you have an infinite loop. Why, because your inductive base case is 0, but you always stay at
n! This is because you recurse onm - 1which is reallyn + 1 - 1I’m surprised as to why this compiles, because it doesn’t include the
reckeyword, which is necessary on recursive functions. To avoid stack overflows in OCaml, you generally switch to a tail recursive style, such as follows:Someone suggested the following edit:
This saves a call to List.rev, I agree.