F# · Lesson 2
Functions
Currying, partial application, lambdas, the pipe |> and composition >>, higher-order and generic functions.
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 needsrec
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
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
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.0is(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:
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# type | TypeScript |
|---|---|
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 list | takes 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.
let addTax (rate: float) (price: float) : float = price * (1.0 + rate)
let addUkVat = addTax 0.2 // float -> float
addUkVat 100.0 // 120.0
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
let isExpensive = fun (price: float) -> price > 100.0
let add = fun a b -> a + b
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:
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)):
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:
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:
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:
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
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 ():
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. Writearea 2.0 3.0. - Missing parentheses around nested calls.
area sqrt 4.0 3.0passessqrtitself as the first argument. Writearea (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 fixespriceat0.2and 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 |> loweris an error.- Value restriction.
let ids = List.map idis 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.Lengthfails if F# doesn't yet knowsis a string. Annotate (fun (s: string) -> s.Length) or pipe the data in first so inference flows left to right.
Cheat sheet
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