1.3 KiB
1.3 KiB
5.1. Simple functions
To create a recursive function we have to use this structure
(*normal function*)
# let f = expr -> 1) evaluate expr ; 2) create & link f to the result
(*recursiv function*)
# let rec f = expr -> 1) create f ; 2) evaluate expr ; 3) link f to the result
Exmple with factorial function
# let rec fact = function
| 0 -> 1
| n -> n * fact(n-1)
# fact 4;;
-: int = 24
⚠️ CAML have a call stack limite (it will block with stack overflow if the limit is reach)
Basic expression
let rec f params =
if stop condition then
stop expression
else
recursive expression
To write a recurvise function we need two things
- There always is a stop case
- The parameters of a recursive call are different then its parent call, and go towards the stop condition
5.2. Down
# let rec countdown n =
if n < 0 then
()
else
begin
print_int n ;
print_newline();
countdown(n-1);
end;;
val countdown = int -> unit = ()
# countdown 3;;
3
2
1
- : unit = ()