F# Journey: Course 3 – Functions

By | April 28, 2014

Back to: F# Journey: Course 2- Type Inference

The concept of a function exists is in F# too. However, it’s slightly different than in C#.

A F# function has a name, list of parameters and a return value. The function itself is assigned to a value with the “let” keyword. The parameter types are inferred by the compiler. But it’s possible to define the parameter type explicitly. The last statement in a function represents the return value.

Here is a “HelloWord” example. The code below defines a function with the name “hello” and one parameter “name”. The name paramter is of type string. (Inferred by compiler)
The function body is indented and has a value named “helloString” of type string which gets concatinated with the “name” parameter. The last statement “helloString + name” is the return value of the “hello” function. “helloExplicit” is the same function but with explicit type definition.

// Types inferred
let hello name =
    let helloString = "Hello "
    helloString + name

// Explicit type definition
let helloExplicit (name : string) : string =
    let helloString : string = "Hello "
    helloString + name

printfn "%s" (hello "Darko")
printfn "%s" (helloExplicit "Darko")

A function always returns a value. The return value can be be ignored if it is not used by the caller.

hello "Darko" |> ignore

F# supports “partial application”. By supplying fewer arguments to a function than expected, F# creates a new one which expects the remaining arguments.
The following “sum” functions expects two arguments. The second functions “sumWithSummand2” calls the “sum” function and passes the first argument “2”.

let sum summand1 summand2 = summand1 + summand2
let sumWithSummand2 = sum 2

printfn "%d" (sum 2 4)
printfn "%d" (sumWithSummand2 4)

Both functions are doing the same, but the signature is different:
val sum : summand1:int -> summand2:int -> int
val sumWithSummand2 : (int -> int)

The “sum” function is curried, which means that the argument list represents a list of single arguments, each returning a function with one less argument than the previous. The “sumWithSummand2” expects one int parameter and a int return value.

To be continued…