Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive functions in OCaml

I have a little problem: I want to solve this problem with OCaml, so I tried this ->

-> let rec somme x = if ( nor (bool_of_int (x mod 3)) (bool_of_int (x mod 5))) then x + (somme x-1) else (somme x-1) ;;

val somme : int -> int = <fun>

-> somme 1000 ;;

Stack overflow during evaluation (looping recursion?).

What have I done wrong ?


New code I tried:

let somme2 x = if (( nor (bool_of_int (x mod 3)) (bool_of_int (x mod 5)))) then x + somme (x-1) else somme (x-1) ;;

let somme x = if x = 0 then x else somme2 x ;;

Same error.

like image 630
unautre Avatar asked Dec 07 '22 05:12

unautre


1 Answers

1) your recusion never stops add a test like if x == 0 then 0 else ... at the beginning

2) you don't put parentheses around your x-1, so ocaml reads (somme x)-1. Write somme (x-1) instead.

like image 197
Gyom Avatar answered Jan 03 '23 18:01

Gyom