# Feeding a function result into a pattern matching lambda expression in F#

May 28, 2017 4 Comments

Say we have an F# function that returns a tuple of two elements:

let isGreaterThan x y = if x > y then (true, x - y) else (false, 0)

…, i.e. we return true and the difference between the two input integers if the first integer is greater. Otherwise we return a false and a 0. Here’s how we can consume this function:

let isGreaterThan x y = if x > y then (true, x - y) else (false, 0) let (gt, diff) = isGreaterThan 10 6 printfn "Is greater: %b, diff: %i" gt diff

…which prints “Is greater: true, diff: 4” in the interactive window. We can feed the result into a lambda expression and branch our logic as follows:

isGreaterThan 18 7 |> (fun outcome -> match outcome with | (true, diff) -> printfn "Difference: %i" diff | (false, diff) -> printfn "Less then")

The tuple from isGreaterThan is fed into the lambda expression which is declared with the fun keyword. “Fun” is followed by a parameter “outcome” which will be populated with the result from the isGreaterThan function. The name of this lambda expression parameter is of course arbitrary. It is then pattern matched against the two possible outcomes based on the boolean return value in the tuple.

The above program prints “Difference: 11” in the interactive window.

View all F# related articles here.

Pingback: F# Weekly #22, 2017 with 2017 F# survey results – Sergey Tihon's Blog

In case you want to shorten it more, you can use `function` instead of `fun outcome -> match outcome with`

that’s coming in the next post on Saturday

You can just to

match isGreaterThan 18 7 with

| (true, diff) -> printfn “Difference: %i” diff

| (false, diff) -> printfn “Less then”

the lambda expression is not really needed: what’s the reason behind it?