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)
}
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)
In this exercise you're going to write a generic (/ magical!) TreasureChest, to store some treasure.
Define a TreasureChest
custom type with a single variant.
The variant should have an associated String
value, which will be used to store the password of the treasure chest.
The variant should also have an associate generic value, which will be used to store the treasure. This value is generic so that the treasure can be anything.
Define a UnlockResult
custom type with two variants.
The first variant should be Unlocked
, and should hold generic value, which will be used to store the treasure.
The second variant should be WrongPassword
, which holds no values.
This function should take two parameters
TreasureChest
generic custom typeString
(for trying a password)This function should check the provided password attempt against the String
in the TreasureChest
.
The function should return a UnlockResult
.
If the passwords match then return Unlocked
with the generic value from the TreasureChest
(the treasure!)
If the passwords do not match then return WrongPassword
.
Sign up to Exercism to learn and master Gleam with 36 concepts, 125 exercises, and real human mentoring, all for free.