Fsharp: Function

By Xah Lee. Date: . Last updated: .
xtodo

Define function

With one arg

// function with 1 arg
let fadd x = x + 1
printfn "%d" (fadd 3)
// 4

With two args

// function with 2 args
let fadd x y = x + y
printfn "%d" (fadd 3 4)
// 7

With local variables

// function with local variables
let ff x =
    let aa = "some"
    let bb = aa + "thing"
    // later var's value can refer to previous (aka chaining)
    x + " " + bb

printfn "%s" (ff "yes")
// yes something
let hh x =
    let (aa, bb) = ("some", "thing")
    x + " " + aa + bb

printfn "%s" (hh "yes")
// yes something

Anonymous function (lambda)

let faddOne = fun x -> x + 1
printfn "%d" (faddOne 3)
// 4
let fadd = fun x y -> x + y
printfn "%d" (fadd 3 4)
// 7

fsharp function