Home

Recursive Functions

   

Description

A recursive function is a function that calls itself. Usually, the function performs an operation first, then calls itself to perform the operation again. Because this can be done over and over again, the function must specify when and how to stop.

To create a recursive function, you use one of the following formulas:

let rec function-name parameter(s) = 
   function-body

or

let rec function1-name paramet(s) =
   function1-body
and function2-name parameter-list =
   function2-body
...

You start with the let rec expression followed by the name of the function with at least one parameter and =.  Based on the first formula, you can define the function in its body. Here is an example:

open System
open System.Windows.Forms

let additionOdd = new Form()
additionOdd.Text   <- "Addition Odd"
additionOdd.Width  <- 225
additionOdd.Height <- 105

let lblMessage : Label = new Label()
lblMessage.Left  <- 18
lblMessage.Top   <- 18
lblMessage.Width <- 202

let rec AdditionalOdd a =
    if a <= 1 then
        1
    else
        a + AdditionalOdd(a - 2)

let number = 9
let result =  AdditionalOdd number

let strResult = sprintf "Sum of odd numbers from 1 to 9: %d" result

lblMessage.Text  <- strResult
additionOdd.Controls.Add lblMessage

let btnClose : Button = new Button()
btnClose.Left <- 122
btnClose.Top  <-  44
btnClose.Text <- "Close"

let btnCloseClick e = additionOdd.Close()
btnClose.Click.Add btnCloseClick
additionOdd.Controls.Add btnClose

do Application.Run additionOdd

This would produce:

Recursive Functions

     
 

Home Copyright © 2009-2015, FunctionX Home