Ge

Generics in Gleam

10 exercises

About Generics

A type is a generic type when it can contain values of any type using a type parameter.

For example, this Box type has the type parameter a (written with lowercase letters).

pub type Box(a) {
  Box(a)
}

The a type parameter is a placeholder for any type, so Box can be used with strings, ints, or any other type.

Box("Hello, Joe!") // The type is Box(String)

Box(42) // The type is Box(Int)

A type can have multiple type parameters by separating them with commas.

pub type Pair(a, b) {
  Pair(a, b)
}

Generic functions

Type parameters can also be used in the arguments of functions.

This function takes a value of the type a and calls twice a function that takes an a and returns a b.

pub fn twice(value: a, f: fn(a) -> b) -> b {
  f(value)
  f(value)
}
// The type is fn(String, fn(String) -> Nil) -> Nil
twice("Hello, Joe!", io.println)
Edit via GitHub The link opens in a new window or tab

Learn Generics

Practicing is locked

Unlock 3 more exercises to practice Generics