Google News
logo
F# - Interview Questions
What is an Recursive Functions in F#?
The rec keyword is used together with the let keyword to define a recursive function.
 
Syntax :
// Recursive function:
let rec function-nameparameter-list =
    function-body

// Mutually recursive functions:
let rec function1-nameparameter-list =
    function1-body

and function2-nameparameter-list =
    function2-body
...
 
Recursive functions - functions that call themselves - are identified explicitly in the F# language with the rec keyword. The rec keyword makes the name of the let binding available in its body.
 
The following example shows a recursive function that computes the nth Fibonacci number using the mathematical definition.
let rec fib n =
    match n with
    | 0 | 1 -> n
    | n -> fib (n-1) + fib (n-2)

 

Methods are implicitly recursive within the type they are defined in, meaning there is no need to add the rec keyword. For example :

type MyClass() =

    member this.Fib(n) =

        match n with

        | 0 | 1 -> n

        | n -> this.Fib(n-1) + this.Fib(n-2)

 

Let bindings within classes are not implicitly recursive, though. All let-bound functions require the rec keyword.

Advertisement