OCaml - Function - Using recursion

OCaml is a fully recursive language. So using recursion is completely natural.
We will see in this example how to create an easy recursion of a classic factorial. This in two different manners.
These two ways of using recursion are strictely the same, the type of the function and the result as well of course.

The first manner to create a recursion function

# let rec factorial n = if n = 0 then 1 else n * factorial(n - 1);;

You can split it to have a better indentation:

# let rec factorial n =
   if n = 0 
     then 1 
   else 
     n * factorial(n - 1);;

After clicking Enter, we will have:

val factorial : int -> int = <fun>

So let's use this function:

# factorial 5;;

- : int = 120

The second manner to create a recursion function

# let rec factorial = function | 0 -> 1 | n -> n * factorial(n - 1);;

Or a really more clear way of displaying:

# let rec factorial = function
    | 0 -> 1
    | n -> n * factorial(n - 1);;

After clicking Enter, we will have:

val factorial : int -> int = <fun>

So let's use this function:

# factorial 5;;

- : int = 120

It was your first recursion! Good job! laugh

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Refresh Type the characters you see in this picture. Type the characters you see in the picture; if you can't read them, submit the form and a new image will be generated. Not case sensitive.  Switch to audio verification.