F# · Lesson 2

Functions

Currying, partial application, lambdas, the pipe |> and composition >>, higher-order and generic functions.

7 min read

In short

  • Every function takes one argument at a time (currying)
  • Supply some arguments now, the rest later (partial application)
  • Configuration first, data last
  • |> pushes a value through steps; >> builds a new function
  • Lambdas are fun x -> ...; recursion needs rec

Functions are the main building block in F#. There are no classes needed to organise code: you write small functions and plug them together. This lesson covers how they're defined, typed and combined.

Defining and calling

▶ Try
let area (width: float) (height: float) : float =
    width * height

let doubled = area 2.0 3.0 * 2.0      // call: name, then arguments separated by spaces
▶ Try
const area = (width: number, height: number): number => width * height;
const doubled = area(2, 3) * 2;
  • Parameters are separated by spaces, both when defining and when calling.
  • Function calls bind tighter than operators: area 2.0 3.0 * 2.0 is (area 2.0 3.0) * 2.0.
  • If an argument is an expression, parenthesise it: area (2.0 + 1.0) (sqrt 9.0).
  • The last expression in the body is the result. There is no return.

You can drop the annotations and let F# infer them. let area width height = width * height is inferred as int -> int -> int, because * defaults to int when nothing says otherwise. Annotating at least the parameters is good practice while learning.

Functions can be defined inside functions, just like nested arrow functions in TS:

▶ Try
let invoiceTotal (net: float) : float =
    let addTax amount = amount * 1.2
    let round2 (amount: float) = System.Math.Round(amount, 2)
    round2 (addTax net)

Reading function types

The type of area is written float -> float -> float. Read the arrows as "takes ... returns ...": the last type is the result, everything before it is a parameter.

F# typeTypeScript
int -> int(x: number) => number
float -> float -> float(a: number) => (b: number) => number
string -> unit(s: string) => void
unit -> int() => number
(int -> bool) -> int list -> int listtakes a function and a list

Currying and partial application

That second row is not a typo. Every F# function really takes one argument at a time. area 2.0 3.0 means "call area with 2.0, get back a function, call it with 3.0." This is called currying, and its superpower is partial application: supply fewer arguments and you get a new function that waits for the rest.

▶ Try
let addTax (rate: float) (price: float) : float = price * (1.0 + rate)

let addUkVat = addTax 0.2        // float -> float
addUkVat 100.0                   // 120.0
▶ Try
const addTax = (rate: number) => (price: number) => price * (1 + rate);
const addUkVat = addTax(0.2);

This shapes how F# code is designed: put configuration parameters first and the data last. addTax rate price, not addTax price rate. That way you can partially apply the configuration and feed the data in later, which is exactly what pipes need.

Lambdas

▶ Try
let isExpensive = fun (price: float) -> price > 100.0
let add = fun a b -> a + b
▶ Try
const isExpensive = (price: number) => price > 100;

fun params -> body is an anonymous function. You'll mostly write them inline as arguments: List.filter (fun p -> p > 100.0) prices. Wrap the lambda in parentheses when passing it.

The pipe operator |>

x |> f means f x. It lets you write a chain of steps in reading order:

▶ Try
let finalPrice =
    80.0
    |> addTax 0.2
    |> min 90.0
    |> string

Without pipes this is string (min 90.0 (addTax 0.2 80.0)), which reads inside-out. TypeScript has no pipe operator (it's still only a proposal), so the closest equivalent is a chain of method calls. Notice how addTax 0.2 is a partially applied function waiting for the price: the pipe supplies it as the last argument. That's why data-last parameter order matters.

Composition >>

f >> g builds a new function that runs f and then g (fun x -> g (f x)):

▶ Try
let trim (s: string) = s.Trim()
let lower (s: string) = s.ToLowerInvariant()

let normalize = trim >> lower    // string -> string
normalize "  Hello "             // "hello"

Use |> when you have a value to push through steps now. Use >> when you want to build a reusable function out of steps for later. (<< composes in the other direction; it's rarely needed.)

Higher-order functions

A function that takes or returns a function is "higher-order". Nothing special is needed. Functions are values:

▶ Try
let applyTwice (f: int -> int) (x: int) : int = f (f x)
applyTwice (fun n -> n * 3) 2                  // 18

let multiplier (factor: int) : int -> int =
    fun n -> n * factor                         // returns a function (a closure)
let triple = multiplier 3

Operators are functions too. Wrap them in parentheses to use them as values: (+) 1 2 is 3, and List.map ((*) 2) [1; 2; 3] doubles each number.

Recursion needs rec

A function can't call itself unless you mark it rec:

▶ Try
let rec factorial (n: int) : int =
    if n <= 1 then 1 else n * factorial (n - 1)

Generics and automatic generalization

If a function doesn't care about a type, F# makes it generic automatically:

▶ Try
let identity x = x                  // 'a -> 'a
let pairWith x y = (x, y)           // 'a -> 'b -> 'a * 'b
let applyBoth f g x = (f x, g x)    // ('a -> 'b) -> ('a -> 'c) -> 'a -> 'b * 'c
▶ Try
const identity = <T,>(x: T): T => x;

Type parameters are written with a leading apostrophe: 'a, 'b, 'T. You can annotate them explicitly: let firstOf (x: 'a) (y: 'a) : 'a = x. You don't need a <T> declaration; F# figures out the type parameters from the annotations.

unit functions

A function with no meaningful input takes ():

▶ Try
let newOrderId () = System.Guid.NewGuid().ToString()
newOrderId ()       // call it with ()

Without the () parameter, newOrderId would be a value computed once, not a function.

Common beginner mistakes

  • Commas in calls. area(2.0, 3.0) passes a tuple. Write area 2.0 3.0.
  • Missing parentheses around nested calls. area sqrt 4.0 3.0 passes sqrt itself as the first argument. Write area (sqrt 4.0) 3.0.
  • Forgetting rec. You'll get "The value or constructor 'factorial' is not defined".
  • Data-first parameter order. With let addTax price rate, prices |> List.map (addTax 0.2) still compiles, but it fixes price at 0.2 and uses each price as the rate: [100.0] gives [20.2], not [120.0]. Put the data last.
  • Partial application by accident. Forget an argument and you get a function instead of a value: "expected to have type 'float' but here has type 'float -> float'" means an argument is missing.
  • |> vs >>. |> needs a value on its left; >> joins two functions. trim |> lower is an error.
  • Value restriction. let ids = List.map id is a value with a generic type, which F# refuses (error FS0030). Give it an explicit parameter: let ids xs = List.map id xs.
  • Multi-line lambdas. A lambda passed as an argument must be in parentheses. If its body continues on the next lines, indent it further than the line where the lambda starts: xs |> List.map (fun x ->, then the body on the next line, four spaces in.
  • Method calls in lambdas need known types. fun s -> s.Length fails if F# doesn't yet know s is a string. Annotate (fun (s: string) -> s.Length) or pipe the data in first so inference flows left to right.

Cheat sheet

▶ Try
let f (a: int) (b: int) : int = a + b    // int -> int -> int
f 1 2                                    // call
let g = f 10                             // partial application: int -> int
fun x -> x * 2                           // lambda
x |> f 1                                 // pipe: f 1 x
let h = trim >> lower                    // composition: fun x -> lower (trim x)
let rec loop n = if n = 0 then 0 else loop (n - 1)   // recursion
let id (x: 'a) : 'a = x                  // generic
(+) 1 2                                  // operator as a function
let now () = System.DateTime.Now         // unit -> DateTime

Practise this lesson

In the app: a short video, 6 exercises checked by real tests and a 11-question concept check. Free with a GitHub account. Running the exercises against their tests needs Pro.

Open in the app