Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

The software running on any modern computer is written in a variety of programming languages. There are machine languages that are executed directly by the hardware of a particular computer. These languages are concerned with the representation of data and control in terms of individual bits of storage and primitive machine instructions. High-level languages, which must be translated to or executed by machine languages, hide concerns about the representation of data as collections of bits and the representation of programs as sequences of primitive instructions. These languages have means of combination and abstraction, such as function definition, that are appropriate to the task of developing complex software.

In this section, we introduce a high-level functional programming language called Gleam. It employs a very similar model of computation to Python’s in terms of functions, names, and environments, but uses only a small set of language features.

Gleam is a relatively new language, reaching v1.0.0 in 2024, that combines characteristics of more established languages, particularly the type inference system of ML (Meta Language) and many of the syntactic conventions of C. Perhaps its most important characteristic for the purposes of this text is its simplicity. The language broadly consists of function definitions, data definitions, conditional expressions, and little else. Therefore, it is a language that can be learned quickly.

To try out examples as you read more, use the Gleam Playground.

Functions

This section gives an overview of Gleam functions. For a more comprehensive description of Gleam functions, read each section of this appendix on Gleam functions and control. This appendix is a subset of the full Gleam language tour, which also covers features of the language that do not appear in this text.

Each Gleam function definition appears in a .gleam module file such as this examples.gleam which contains all of the examples from this section. Functions are introduced using fn and can be marked pub to indicate that they are public, which means that they can be imported by other modules. Comments in Gleam begin with // and docstrings for functions begin with ///.

/// Triple an integer
pub fn triple(x: Int) -> Int {
  3 * x
}

As with Python type hints, each formal parameter and the return value can be annotated with a type. Specific types are always capitalized, and Int is Gleam’s built-in integer type.

Unlike Python, there is no return keyword or equivalent statement. Instead, function bodies end with an expression that determines the return value.

Also unlike Python, this triple function can only be called on an Int value and must return an Int. A Gleam program cannot run without first confirming that all implicit and explicit type annotations are respected.

Let. A let binds a name to the value of an expression, much like Python’s assignment statement.

/// Sum the squares of x and y.
pub fn sum_squares(x: Int, y: Int) -> Int {
  let x2 = x * x
  let y2 = y * y
  x2 + y2
}

Blocks. Gleam uses braces to create blocks of code, which end in an expression that provides the value of the block.

/// Compute a*x*x + b*x + c
pub fn quadratic(x: Int, a: Int, b: Int, c: Int) -> Int {
  let ax2 = {
    let x2 = x * x
    a * x2
  }

  // ax2 is in scope here, but x2 is not
  ax2 + b * x + c
}

Blocks are used instead of parentheses to express the order of operations in a complex arithmetic expression. Therefore, parentheses can be reserved for other purposes such as defining and calling functions.

/// x + 1, doubled
pub fn add_one_and_double(x: Int) -> Int {
  { x + 1 } * 2
}

A name assigned within a block using let cannot be accessed outside of that block.

Strings and Output

Gleam string literals are text within double quotes. Two strings can be concatenated with the <> operator, and the gleam/string module provides a variety of string manipulation functions. Printing strings involves importing the gleam/io module, then calling io.println, which displays a string on its own line.

import gleam/io
import gleam/string

pub fn print_thrice(s: String) {
  io.println(s)
  io.println(s)
  io.println(s)
}

/// cheer("bears") prints
/// Go BEARS!
/// Go BEARS!
/// Go BEARS!
pub fn cheer(mascot: String) {
  print_thrice("Go " <> string.uppercase(mascot) <> "!")
}

To print a value that is not a string, convert it to a string. For example, after import gleam/int, the expression io.println(int.to_string(12)) prints 12 using int.to_string. These modules are all part of Gleam’s standard library.

Alternatively, an echo expression displays any value along with the line number in the program, and evaluates to the value that was displayed. The intended use of echo is to display intermediate values while debugging.

Higher-Order Functions

Functions are values and therefore have types. The type of a function in Gleam specifies how many arguments it takes, their types, and the type of value it returns. In order to describe the type of a function that is either passed into or returned from another function, we can write a function type, which also starts with fn but does not have a name. For example, fn(Int, Int) -> Int is a type of function that takes two integers and returns one.

/// Combine x, y, and z by calling f on x and y, then z.
pub fn combine(x: Int, y: Int, z: Int, f: fn(Int, Int) -> Int) -> Int {
  f(f(x, y), z)
}

Anonymous functions also use the fn keyword and behave similarly to Python’s lambda expressions. For example, fn(x, y) { x + y } defines a function that adds two integers. The twelve function uses combine to add 3, 4, and 5.

/// 3 + 4 + 5
pub fn twelve() -> Int {
  combine(3, 4, 5, fn(x, y) { x + y })
}

The body of an anonymous function can refer to names in its enclosing scope. However, unlike Python, binding the same name again with let after a function has been created does not affect that function.

/// Calling three() returns 3, not 4.
pub fn three() -> Int {
  let x = 3
  let f = fn() { x }
  let x = 4
  f()
}

Generic functions. A lowercase type name is used to express that the same type appears multiple times in a function’s signature but can be any type, which makes the function generic. For example, this twice function can take any function that takes and returns the same type. The name t refers to that type each time it appears. It returns a value of that same type. It can be used on functions that take and return integers or strings.

/// Call a function f twice on x.
fn twice(f: fn(t) -> t, x: t) -> t {
  f(f(x))
}

/// Echoes 12 and then "Hello!!", each after its line number.
pub fn test_twice() {
  let add_one = fn(x) { x + 1 }
  let exclaim = fn(x) { x <> "!" }

  echo twice(add_one, 10)
  echo twice(exclaim, "Hello")
}

Control

A means of control in a programming language determines what expressions are evaluated and when. Defining and calling functions is the most common way to control the flow of execution of a program, and some sort of if statement or expression, called a conditional, is the second most common means of control. Gleam has the case expression, which matches the value of a header expression against patterns and evaluates to the value of one of several alternatives: the one for the first pattern that matches the value of the header expression.

The simplest case has a header that evaluates to True or False.

/// Divide n by d if d evenly divides n, and otherwise return n.
pub fn attempt_to_divide(n: Int, d: Int) -> Int {
  case n % d == 0 {
    True -> n / d
    False -> n
  }
}

The header can evaluate to any type of value, and the patterns can match specific values or alternatives. The _ discard pattern matches any value. In this example, "Few" is returned for inputs 2, 3, and 4.

pub fn describe_positive(n: Int) -> String {
  case n {
    1 -> "One"
    2 | 3 | 4 -> "Few"
    _ -> "Many"
  }
}

A guard is an if following a pattern that specifies a condition under which the pattern is matched. If a guard condition is not met, then evaluation continues to the next pattern in search of a match. For example, "Negative" is returned only for negative inputs even though the pattern _ matches any number.

pub fn describe(n: Int) -> String {
  case n {
    _ if n < 0 -> "Negative"
    0 -> "None"
    1 -> "One"
    2 | 3 | 4 -> "Few"
    _ -> "Many"
  }
}

Two or more expressions, separated by commas, can appear in the header of a case expression. These are called multiple subjects. Each pattern then has one comma-separated part for each subject, and each part is matched against the value of the corresponding subject.

/// Return True if either a or b is True but not both, and False otherwise.
pub fn exclusive_or(a: Bool, b: Bool) -> Bool {
  case a, b {
    True, False -> True
    False, True -> True
    _, _ -> False
  }
}

Boolean values a and b can be combined using a && b, which is True if both are True, or a || b, which is True if either is True. If a is True, then !a is False, and vice versa. The gleam/bool module provides other functions on booleans.

Iteration

Gleam has no for or while, and so iteration must be expressed using recursion. For example, here’s a function that computes n factorial for nonnegative n.

/// n * (n-1) * (n-2) * ... * 1
pub fn factorial(n: Int) -> Int {
  case n {
    _ if n <= 0 -> 1
    _ -> n * factorial(n - 1)
  }
}

When a function is implemented using a recursive helper function, the helper is defined as a top-level function rather than within the body of another function. If a helper function is primarily intended to serve as part of the implementation of another function, rather than for general purposes, it is not marked pub.

/// Return the number of ways that a non-decreasing sequence of positive integers can sum to n.
/// E.g., count_all_partitions(5) counts 5, 1+4, 2+3, 1+1+3, 1+2+2, 1+1+1+2, and 1+1+1+1+1.
pub fn count_all_partitions(n: Int) -> Int {
  count_partitions(n, n)
}

/// Count the ways of summing to n using parts up to m to implement count_all_partitions.
fn count_partitions(n: Int, m: Int) -> Int {
  case n {
    0 -> 1
    _ if n < 0 || m == 0 -> 0
    _ -> count_partitions(n - m, m) + count_partitions(n, m - 1)
  }
}

Data

Like Python, Gleam has container types for sequences and dictionaries and also allows for user-defined types. Unlike Python, Gleam does not include any value mutation operations for any of its types, and user-defined types are also immutable.

Lists

The built-in List type in Gleam is a linked list of items that all have the same type. A list can be created using a list literal: an expression starting and ending with brackets that contains expressions. Two lists are equal if they have the same length and all corresponding elements are equal.

let s = [1, 2, 2 + 1]
assert s == [1, 2, 3]

A list literal can contain one expression for the rest of the list, following .. and just before the closing bracket. There can only be one .. in a list literal, but the expression after .. can be another list literal or any other expression that evaluates to a list.

let t = [4, 5, ..s]
let u = [3 + 3, ..[7, ..t]]
assert u == [6, 7, 4, 5, 1, 2, 3]

The items of a list cannot be accessed without first checking that they exist, typically using a case expression. The patterns of the case expression must together describe all possible lists. As a result, any program that attempts to access an item at a particular index must also describe what to do in the event that the list does not contain enough elements to have an item at that index.

List patterns use the same syntax as list literals. However, they have an opposite purpose: a list literal creates a list out of items and (optionally) the rest of the list, while a list pattern gives names to the items and (optionally) the rest of existing lists. In the last_two example below, [a, b] matches any list with exactly two items and gives the name a to the first item and b to the second. The pattern [a] matches lists with exactly one item and gives the name a to the first (and only) item. The pattern [_, ..rest] gives the name rest to the rest of the list following the first item, which is not named.

/// Return the sum of the last two items of a list of integers.
/// If either of those items doesn't exist, use default in their place.
fn last_two(s: List(Int), default: Int) -> Int {
  case s {
    [a, b] -> a + b
    [a] -> a + default
    [] -> default + default
    [_, ..rest] -> last_two(rest, default)
  }
}

The name of the rest of the list after .. can be omitted. The pattern [a, b, ..] in the first_two function below matches any list with at least two items.

/// Return the sum of the first two items of a list of integers.
/// If either of those items doesn't exist, use default in their place.
fn first_two(s: List(Int), default: Int) -> Int {
  case s {
    [a, b, ..] -> a + b
    [a] -> a + default
    [] -> default + default
  }
}

The Gleam standard library contains many list functions, including ones that correspond to Python built-in functions: map, filter, all, any, and length. The Gleam map and filter functions take a list as the first argument and a function as the second.

import gleam/list

/// Return a list of all the odd items in s doubled.
fn double_each_odd(s: List(Int)) -> List(Int) {
  list.map(list.filter(s, fn(n) { n % 2 != 0 }), fn(n) { 2 * n })
}

Pipe operator. Functions in the Gleam standard library typically take as their first argument the kind of data with which they are associated, so list functions take a list first. The pipe operator |> is designed to allow a sequence of such operations to be written in the order that they are applied. A pipe expression evaluates the expression to the right of the pipe after inserting the expression to the left of the pipe as the first operand.[1] The drop function returns a list that is the given list with up to the given number of elements removed from the front of the list.

import gleam/list

/// Return a list of the even items in s after the first k, tripled.
fn triple_each_even_after(s: List(Int), k: Int) -> List(Int) {
  s
  |> list.drop(k)
  |> list.filter(fn(n) { n % 2 == 0 })
  |> list.map(fn(n) { 3 * n })
}

Generic lists. Using a lowercase type variable for the item type of a list allows for functions that can operate on any type of list. For example, the alternating function below returns whether a list contains just two values alternating: [x, y, x, y, x, y, x, ...] for some values x and y.

fn alternating(s: List(a)) -> Bool {
  case s {
    [] -> True
    [x, _, z, ..] if x != z -> False
    [_, ..rest] -> alternating(rest)
  }
}

Tuples

A tuple combines a fixed number of items, which can have different types. A tuple literal is an expression starting with #( and ending with ) that contains comma-separated expressions. The items of a tuple can be accessed by position: .0 for the first item, .1 for the second, and so on.

fn sum_squares(x: Int, y: Int) -> Int {
  let squares = #(x * x, y * y)
  squares.0 + squares.1
}

A let statement can give new names to the items of a tuple using a tuple pattern, which has the same syntax as a tuple literal.

fn sum_squares(x: Int, y: Int) -> Int {
  let squares = #(x * x, y * y)
  let #(x2, y2) = squares
  x2 + y2
}

A case pattern can also give a name to values within a tuple. The type of a tuple lists the types of its items, so #(Int, Int) is the type of a tuple containing two integers. In the show_fraction example below, a fraction is represented as a tuple containing a numerator and a denominator.

import gleam/int

/// Convert a fraction (numerator, denominator) to a string.
fn show_fraction(f: #(Int, Int)) -> String {
  case f {
    #(_, 0) -> "undefined"
    #(n, 1) -> int.to_string(n)
    #(n, d) -> int.to_string(n) <> "/" <> int.to_string(d)
  }
}

pub fn show_example() {
  assert show_fraction(#(3, 4)) == "3/4"
  assert show_fraction(#(5, 1)) == "5"
  assert show_fraction(#(2, 0)) == "undefined"
}

Results

The built-in Result type has two variants: Ok and Error. It is used to represent the result of a process that might produce a value (the Ok variant) or might fail to produce a value (the Error variant). The Ok and Error variants each have a field: the value that resulted, or a value representing the error that occurred. If there is no data associated with the error, then its field has type Nil.

Many standard library functions return a result. For example, the list.first function returns the first item in a list, but since the list may be empty, it returns a Result.

pub fn first(list: List(a)) -> Result(a, Nil)

A case expression can pattern match the two variants of this Result, determining what to do if there is a first element and if there is not.

/// Return the value in result if there is one, or else default.
fn value_or(result: Result(Int, Nil), default: Int) -> Int {
  case result {
    Ok(value) -> value
    Error(Nil) -> default
  }
}

The first_two function from above can be written using value_or to supply the default for each of the first two items, which are the first item of s and the first item after dropping one item from s.

fn first_two(s: List(Int), default: Int) -> Int {
  let a = s |> list.first |> value_or(default)
  let b = s |> list.drop(1) |> list.first |> value_or(default)
  a + b
}

The standard library function result.unwrap behaves just like value_or, but it works for any Result.

Returning Result values for every function that may not succeed is how Gleam implements a general programming approach called value-based error handling, which is also standard practice in Go, Rust, and many other languages. It contrasts with exception-based error handling in Python, which allows operations that may fail, such as s[0] (since s could be empty), and does not require error handling.

Dicts

A dictionary holds key-value pairs. The Gleam Dict type holds them in an unpredictable order, but provides efficient retrieval of a value for its key.

An empty dictionary is created by dict.new and can be extended using dict.insert. A non-empty dictionary is created from a list of key-value tuples using dict.from_list. The value for a key is retrieved using dict.get, which returns a Result.

pub fn from_list(list: List(#(k, v))) -> Dict(k, v)

pub fn get(from: Dict(k, v), get: k) -> Result(v, Nil)

The invert function below builds a dictionary from each output of f to its input, then returns a function that looks up the input for an output. Its result is an Error for an output that f never produced from inputs.

import gleam/dict
import gleam/list

/// Return the inverse of f for the outputs of f on inputs:
/// invert(f, inputs)(f(x)) == Ok(x) for each x in inputs.
pub fn invert(f: fn(a) -> b, inputs: List(a)) -> fn(b) -> Result(a, Nil) {
  let inverse = dict.from_list(list.map(inputs, fn(x) { #(f(x), x) }))
  fn(y) { dict.get(inverse, y) }
}

pub fn invert_example() {
  let sqrt = invert(fn(x) { x * x }, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
  assert sqrt(49) == Ok(7)
  assert sqrt(50) == Error(Nil)
}

Algebraic Data Types

A product type builds a new type by combining values of other types. A tuple type such as #(Int, Int) is a product type: each of its values contains an integer and another integer. A sum type builds a new type by choosing among alternatives. Result is a sum type: each of its values is either an Ok or an Error. An algebraic data type is a type formed using these two methods.

A user-defined type is created by a type statement that lists one or more variants. Each variant has a capitalized name and (optionally) fields, each with a type and optionally a name. A field in Gleam is similar to an instance attribute in Python. The name of a variant is also a constructor: a function that takes the fields as arguments and returns a value of the type. Each value of a user-defined type is called a record.

For example, let’s say a user of a system needs either an email address or a phone number (or both). The User type below describes a user with a name, an email address, and a phone number. The Option type from the standard library is a sum type with two variants: Some(value) when there is a value and None when there is not.

import gleam/option.{type Option}

pub type User {
  User(name: String, email: Option(String), phone: Option(Int))
}

However, this type doesn’t enforce the constraint that a user should have either an email address or phone number (or both). The expression User("Oski", None, None) creates a user with neither.

Using both product and sum types together makes a user with no email or phone a type checking violation: an error that is caught before the program runs. Below, Contact is a sum type with three variants, and each variant is a product of its fields. A User combines a name and a Contact, and every Contact includes an email address, a phone number, or both.

pub type Contact {
  EmailOnly(email: String)
  PhoneOnly(phone: Int)
  Both(email: String, phone: Int)
}

pub type User {
  User(name: String, contact: Contact)
}

The fields of a type with only one variant can be accessed using dot expressions. For example, user.contact is the Contact of a User named user. A case pattern gives local names to the fields (similar to Python attributes) of each variant. In the contact function below, the alternative pattern EmailOnly(e) | Both(e, _) gives the name e to the email address of either an EmailOnly or a Both contact.

import gleam/int

/// Return a link that can be used to contact a user.
pub fn contact(user: User) -> String {
  case user.contact {
    EmailOnly(e) | Both(e, _) -> "mailto:" <> e
    PhoneOnly(n) -> "tel:" <> int.to_string(n)
  }
}

pub fn contact_example() {
  let oski = User("Oski", EmailOnly("oski@berkeley.edu"))
  assert contact(oski) == "mailto:oski@berkeley.edu"
}

Fields can also be accessed through dot expressions. If the field exists for all variants, it can be accessed on any record of that type. However, if a field only exists for some variants (such as email: String in this example), the dot expression must be within a case that matches the variant that has that field. The pattern EmailOnly(..) matches any EmailOnly value without naming its fields, and as c gives the name c to the whole value that was matched. Within the EmailOnly and Both branches, c.email is an email address. Within the PhoneOnly branch, c.phone is a phone number, but c.email would be a type checking violation.

pub fn contact(user: User) -> String {
  case user.contact {
    EmailOnly(..) as c -> "mailto:" <> c.email
    Both(..) as c -> "mailto:" <> c.email
    PhoneOnly(..) as c -> "tel:" <> int.to_string(c.phone)
  }
}

Type variables. A type can use a lowercase word (typically just a letter) as a type variable, which stands for any type and is used to indicate that the same type appears in multiple places. For example, a tree is a label and a list of branches, and a leaf is a tree with an empty list of branches. The labels must all be the same type, but they can be any type. This definition is expressed by this Tree type:

pub type Tree(a) {
  Tree(label: a, branches: List(Tree(a)))
}

For convenience, we can introduce a leaf function that returns a Tree with no branches. Again, we use a type variable to indicate that the type of the input label determines the type of the resulting tree’s label.

pub fn leaf(label: a) -> Tree(a) {
  Tree(label, [])
}

Then a Tree with the structure below can be constructed as Tree(1, [Tree(2, [leaf(3), leaf(4)]), Tree(5, [leaf(6)])]).

Diagram of the tree Tree(1, [Tree(2, [Tree(3, []), Tree(4, [])]), Tree(5, [Tree(6, [])])])

The sum_labels function returns the sum of the labels in a Tree of integers.

import gleam/int
import gleam/list

/// Return the sum of the labels in a tree of integers.
pub fn sum_labels(t: Tree(Int)) -> Int {
  t.label + int.sum(list.map(t.branches, sum_labels))
}

The remove_leaf function returns a Tree without its leftmost leaf if it has more than one node.

/// A new tree without its leftmost leaf; a tree that is a leaf is unchanged.
pub fn remove_leaf(tree: Tree(a)) -> Tree(a) {
  case tree {
    Tree(label, [Tree(_, []), ..rest]) -> Tree(label, rest)
    Tree(label, [first, ..rest]) -> Tree(label, [remove_leaf(first), ..rest])
    Tree(_, []) -> tree
  }
}

The pattern [Tree(_, []), ..rest] nests a record pattern inside a list pattern: it matches a list whose first item is a leaf, and gives the name rest to the branches after it. Arms of a case are tried in order, so the second arm is reached only when the first branch is not a leaf, and remove_leaf then removes the leftmost leaf of that first branch instead. A tree with no branches matches neither of the first two arms and is returned unchanged.

Applying remove_leaf to the tree above removes the leaf labeled 3, giving Tree(1, [Tree(2, [leaf(4)]), Tree(5, [leaf(6)])]).

Diagram of the tree Tree(1, [Tree(2, [Tree(4, [])]), Tree(5, [Tree(6, [])])])
Footnotes
  1. To insert the left side somewhere other than the first operand, use an underscore as a placeholder for it on the right side. For example, 2 |> int.subtract(10, _) evaluates to int.subtract(10, 2), which is 8, while 2 |> int.subtract(10) evaluates to int.subtract(2, 10), which is -8.