Basic function declaration in F#
January 21, 2017 Leave a comment
We declare functions in F# using the “let” keyword. F# functions are quite spartan compared to their C# and Java counterparts. There are no parentheses, curly braces, commas, semicolons. Type declaration is optional and there’s no need for the “return” keyword if the function returns something. F# functions are similar to LINQ statements we use in C#.
The anatomy of a basic function is the following:
- The “let” keyword
- Followed by the function name
- Followed by input parameters if any
- Then comes the equality operator ‘=’ which acts as an assignment operator in this case
- Finally we have the function body assigned to the function with the assignment operator
Here’s a simple function that increments the input parameter x by one:
let increment x = x + 1
There’s no need to explicitly declare the type of x, the F# compiler can figure it out. The C# equivalent of the same function would like the following:
private int Increment(int x) { return x + 1; }
The return statement always comes last. Here’s a bloated version of the increment function:
let increment x = printfn "Your input parameter was %i" x let res = x + 1 printfn "The result is %i" res x + 1
If the function is void then we simply omit any last return statement:
let thisIsAVoidFunction = printfn ("Hello world")
The above example also shows a function with no input parameters.
Here’s how we can call these functions from the F# main function:
let increment x = printfn "Your input parameter was %i" x let res = x + 1 printfn "The result is %i" res x + 1 let thisIsAVoidFunction = printfn ("Hello world") [<EntryPoint>] let main argv = thisIsAVoidFunction printfn "%i" (increment 2) 0 // return an integer exit code
When calling increment we just supply the input parameter afterwards with a whitespace in between.
The “%i” bit means that we want to print the result of the increment function as an integer. It’s an example of string formatting in F#.
We can declare the input parameter type explicitly if needed using a colon following by the type descriptor:
let increment x:int = x + 1
Note that the F# compiler looks at the elements in the source file from the top. The functions must be declared before they are used. The following will result in an exception:
[<EntryPoint>] let main argv = thisIsAVoidFunction printfn "%i" (increment 2) 0 // return an integer exit code let thisIsAVoidFunction = printfn ("Hello world")
It will produce the following compiler error:
The value or constructor ‘thisIsAVoidFunction’ is not defined
The function can of course have multiple input parameters. They follow the function name with a white space in between:
let addThreeNumbers x y z = x + y + z
…and here’s how to call it:
addThreeNumbers 4 6 9
View all F# related articles here.