Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 37 ยท Functions and Pipelines

Lambdas and Higher-Order Functions in F#: map, filter, fold

Use F# lambda expressions, pass functions as arguments, return functions from functions, and learn map, filter, fold, closures and function values with clear examples and diagrams.

In F#, a function is a value like any other: you can store it, pass it to another function and return it as a result. A function that takes or returns functions is called a higher-order function. This idea is behind List.map, List.filter and List.fold, and it is the way F# programmers separate what to repeat from what to do each time. This lesson covers lambda syntax, functions as arguments and results, the big three (map, filter, fold) and closures.

Lambda expressions

A lambda is a function without a name, written with fun, the parameters, an arrow and the body:

FSHARP
fun x -> x * x
fun a b -> a + b
fun (name: string) -> name.Length

Give a lambda a name with let and it becomes an ordinary function; these two are identical:

FSHARP
let square1 x = x * x
let square2 = fun x -> x * x

Lambdas are most useful as short arguments:

FSHARP
[ 1; 2; 3 ] |> List.map (fun x -> x * 10)        // [10; 20; 30]

Wrap a lambda in parentheses when it is an argument. For a multi-line body, indent it:

FSHARP
[ 1; 2; 3 ]
|> List.map (fun x ->
    let y = x * 10
    y + 1)

Pattern matching in a lambda parameter lets you unpack tuples directly:

FSHARP
[ (1, "a"); (2, "b") ] |> List.map (fun (n, s) -> $"{s}{n}")    // ["a1"; "b2"]

The function keyword is shorthand for a lambda that immediately matches its argument:

FSHARP
let describe = function
    | 0 -> "zero"
    | n when n < 0 -> "negative"
    | _ -> "positive"

Functions as arguments

Write a function that takes another function to customise its behaviour:

FSHARP
let applyTwice f x = f (f x)

applyTwice (fun n -> n + 3) 10         // 16
applyTwice (fun (s: string) -> s + "!") "hey"   // "hey!!"

Its type is ('a -> 'a) -> 'a -> 'a: it takes a function from 'a to 'a, a value of type 'a, and returns an 'a. Such generic higher-order functions are the heart of library design.

A practical example is a function that repeats an action, parametrised by what to do:

FSHARP
let repeat times action =
    for i in 1 .. times do
        action i

repeat 3 (fun i -> printfn "Round %d" i)

Functions that return functions

FSHARP
let makeGreeter greeting =
    fun name -> $"{greeting}, {name}!"

let hello = makeGreeter "Hello"
let hola = makeGreeter "Hola"
hello "Ada"     // "Hello, Ada!"
hola "Ada"      // "Hola, Ada!"

This is partial application in disguise, from Currying and partial application, and it also demonstrates a closure: hello remembers the greeting it was built with.

The big three: map, filter, fold

flowchart LR
    A["map f"] --> B["transform every item"]
    C["filter p"] --> D["keep items where p is true"]
    E["fold f s"] --> F["combine all items into one value"]

Three functions cover most loops.

map transforms each element, keeping the length:

FSHARP
[ "a"; "bb"; "ccc" ] |> List.map String.length      // [1; 2; 3]

filter keeps items satisfying a predicate (a function returning bool):

FSHARP
[ 1 .. 10 ] |> List.filter (fun n -> n % 3 = 0)     // [3; 6; 9]

fold reduces a list to a single value. It takes a combining function, a starting state and the list:

FSHARP
let total = [ 1; 2; 3; 4 ] |> List.fold (fun acc x -> acc + x) 0       // 10
let longest = [ "a"; "abc"; "ab" ] |> List.fold (fun acc s -> max acc s.Length) 0   // 3

The lambda receives the accumulated state and the next element, and returns the new state. fold is the general form: sum, length, max and even map can be written with it.

FSHARP
let reverse list = List.fold (fun acc x -> x :: acc) [] list
reverse [ 1; 2; 3 ]      // [3; 2; 1]

Variants: List.reduce (no initial state, fails on empty lists), List.foldBack (right to left), List.scan (keeps every intermediate state), List.sumBy, List.maxBy and List.collect (map then flatten). They appear again in Lists.

Predicates and comparers

Many functions take a predicate 'a -> bool: List.filter, List.exists, List.forall, List.tryFind, List.partition. Others take a key selector: List.sortBy, List.groupBy, List.maxBy.

FSHARP
let words = [ "pear"; "fig"; "banana" ]
words |> List.sortBy String.length          // ["fig"; "pear"; "banana"]
words |> List.exists (fun w -> w.Length > 5)     // true

Closures and captured values

A lambda can use values from the scope where it was created. Those values live as long as the function does:

FSHARP
let threshold = 3
let big = [ 1; 5; 2; 8 ] |> List.filter (fun n -> n > threshold)    // [5; 8]

Recall the restriction from Values and let bindings: a closure cannot capture a let mutable local. Capture an immutable value, a ref cell, or restructure with fold.

Method groups and shorthand

When a lambda only forwards its argument to one function, pass the function itself:

FSHARP
[ "a"; "b" ] |> List.map (fun s -> String.length s)   // verbose
[ "a"; "b" ] |> List.map String.length                // better

For members of a type, use _.Property (F# 8 shorthand):

FSHARP
type Person = { Name: string; Age: int }
let people = [ { Name = "Ada"; Age = 36 }; { Name = "Alan"; Age = 41 } ]
people |> List.map _.Name        // ["Ada"; "Alan"]

C# stand-ins

C# has lambdas and delegates (Func) and LINQ's Select, Where and Aggregate, which correspond to map, filter and fold.

C# C# stand-in: map, filter and fold with LINQ

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# C# stand-in: functions as values and closures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does fun x -> x * 2 create?

    fun creates a function without a name, which you can pass around or bind with let.
  2. 2. What is [1; 2; 3; 4] |> List.fold (fun acc x -> acc + x) 0?

    fold starts at 0 and adds each element, giving 10.
  3. 3. Which function keeps only elements for which a predicate is true?

    filter keeps matching elements; map transforms; fold combines.
  4. 4. What is a higher-order function?

    Higher-order functions treat functions as values.

Summary

  • fun args -> body creates a lambda; function is a lambda that matches its single argument.
  • Functions are values: pass them in, return them, store them.
  • List.map, List.filter and List.fold (and their relatives) replace most manual loops.
  • Closures remember the values they captured; avoid capturing let mutable locals.
  • Pass named functions directly (List.map String.length) instead of wrapping them in lambdas.

Next: Lists