Working With Functions in FSharp

Introduction: A function is a sub program, it groups code into a single unit and reduces the complexity of large code. It provides a modular approach in the programming language.

Defining Function:
In F#, a function is defined with the let keyword. Syntax for a function definition is given below

fuction definition

Like, let add x  y = x + y.

If the function is recursive, then the function definition starts with let rec keyword. It's syntax is given below

     let rec function_name parameter_list = Function_body   

Like, rec fact x= function body

Function Calling: Write the following code.

let add a b = a + b
sub a b = a - b
mul a b = a * b
div a b = a / b

result result1 result2 result3 result4 =
    printfn "Addition :      %i" result1
    printfn "Substraction:   %i" result2
    printfn "Multiplication: %i" result3
    printfn " Division:      %i" result4
result (add 42 6) (sub 42 6) (mul 4 5) (div 10 2)


fuction calling

Function with Returning Value: We make a function for adding two numbers in F# by writing the below code.

let add x y=x + y
result=add 5 5
printfn "%d" result

Here, add is the name of a function with two parameter x and y. It is a simple example of a function for addition of two numbers. A function is called by specifying its parameter with the function name as " add 5 5 " and its value is assigned to result. The output will look like the below figure.

fuction with returning value

Recursive Function: A recursive function is a function which makes calls to itself. The function calls itself within its definition. In F#, the declaration of a recursive function begins with the rec keyword after the let keyword. Now we will make a recursion function to calculate a factorial. We write the following code

rec fact x= if x<=1 then 1 else x*fact(x-1)
result= fact 5
printfn "factorial : %d" result

The output will look like the following figure.

recursive function in f#

Anonymous Functions: When there is no need to give a name to a function, we declare the function with the fun keyword. This type of function is also known as lambda function or lambdas. In this type of function, argument list and function body is separated by the token ->.
We write the following code

x = (fun x y -> x + y) 5 7
printfn "%d" x

The output will look like the following figure.

anonymous function in f#