aboutsummaryrefslogtreecommitdiff
path: root/std/default/options.pk
blob: 3aaea495767d3eea8f39c7fe906e56d406106e7f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
## std/options: Optional types.
## This module is imported by default.

import std/format

pub type Option[T] = union
  Some: T
  None

pub func is_some[T](self: Option[T]): bool =
  self of Some(_)
pub func is_none[T](self: Option[T]): bool =
  not self.is_some

## Converts an Option[T] to a Result[T, E] given a user-provided error.
pub func err[T, E](self: Option[T], error: E): Result[T, E] =
  if self of Some(x):
    Okay(x)
  else:
    Error(error)

## Applies a function to T, if it exists.
pub func map[T, U](self: Option[T], proc: T -> U): Option[U] =
  if self of Some(x):
    Some(x.proc)
  else:
    None
## Converts T to a None, if proc returns false and it exists.
pub func filter[T](self: Option[T], proc: T -> bool): Option[T] =
  if self of Some(x) and proc(x):
    Some(x)
  else:
    None

## Applies a function to T, if it exists. Equivalent to .map(func).flatten.
pub func flatmap[T, U](self: Option[T], proc: T -> Option[U]): Option[U] =
  if self of Some(x):
    x.proc
  else:
    None
## Converts from Option[Option[T]] to Option[T].
pub func flatten[T](self: Option[Option[T]]): Option[T] = # todo: better name?
  match self
  of Some(Some(x)):
    Some(x)
  of _:
    None

## Returns the inner value or a default.
pub func get_or[T](self: Option[T], default: T): T =
  if self of Some(x): x
  else: default
## Directly accesses the inner value. Throws an exception if None.
pub yeet func `!`[T](self: Option[T]): T =
  if self of Some(x): x
  else: raise Exception # todo: syntax??

## Indirect access. Propagates None.
pub macro `?`[T](self: Option[T]) =
  quote:
    match self
    of Some(x): x
    of None: return None

## Overloads the == operation for use on Options.
pub func `==`[T](a, b: Option[T]): bool =
  match (a, b)
  of (Some(x), Some(y)):
    x == y
  of _:
    false

## Overloads the str() function for use on Options.
pub func str[T](self: Option[T]): str =
  if self of Some(x):
    fmt("some({})", x.str)
  else:
    "none"

examples:
  let x = Some(42)
  if x of Some(y):
    assert x! == y

# references:
# https://nim-lang.github.io/Nim/options.html
# https://doc.rust-lang.org/std/option/enum.Option.html