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

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.

I'm a .NET/Java developer living and working in Stockholm, Sweden.

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

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

2. giuliohome says:

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?

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.