.nib std
nib 0.3.1-pre

Pre-release documentation. This describes nib 0.3.1-pre, which is on main and has no release yet: what it documents beyond 0.3.0 may change before it ships.

module use "std/option.nib"

Option

A value that may be absent: Option.Some(x) or Option.None, with the helpers that read one without a match.

Option<'t> says "a 't, or nothing" in the type, so a missing answer is a value the caller handles rather than a sentinel like -1 or an error it has to remember to catch. It is an ordinary data with two constructors: from outside this module they are written Option.Some(x) and Option.None, and the type is Option.Option<'t>.

The usual way to take one apart is a match, which must name both arms — the compiler refuses a match on an Option that forgets the None case.

let describe = { o ->
  match o
    Some(n) => "got {n}"
    None => "nothing"
  end };
(describe(Option.Some(7)), describe(Option.None))
("got 7", "nothing")

The helpers below cover the common cases without a match. Vec.Opt and Map.Opt answer Options for the Vec and Map reads that would otherwise raise.

Data

dataOption
data Option<'t> where Some('t); None

Some(x) holds a value; None holds nothing. None has no payload, so it fits an Option of any element type.

let some: Option.Option<Int> = Option.Some(3);
let none: Option.Option<Int> = Option.None;
(some, none)
(Option.Some(3), Option.None)

Functions

func unwrap_or :: o: Option<'t>, fallback: 't -> 't

The value inside a Some, or fallback for a None. There is no unwrap that fails on None: you always say what the empty case means. To treat a None as an error, match and raise where failing is the point.

(Option.unwrap_or(Option.Some(5), 0), Option.unwrap_or(Option.None, 0))
(5, 0)
funcmap
func map :: o: Option<'a>, f: pin ('a) -> 'b -> Option<'b>

Applies f to the value inside a Some and wraps the result; a None stays None and f is not called. The result may be a different type from the input.

let len = { s -> String.length(s) };
(Option.map(Option.Some("nib"), len), Option.map(Option.None, len))
(Option.Some(3), Option.None)
func is_some :: o: Option<'t> -> Bool

true for a Some, false for a None.

(Option.is_some(Option.Some(1)), Option.is_some(Option.None))
(true, false)
func is_none :: o: Option<'t> -> Bool

true for a None, false for a Some. The opposite of Option.is_some.

(Option.is_none(Option.Some(1)), Option.is_none(Option.None))
(false, true)