aboutsummaryrefslogtreecommitdiff
path: root/src/Result.gleam
blob: 83f5651754c07ea055f9a2c45da0c1cfa6091a4f (plain)
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
module Result
  exposing Result(..), is_ok/1, is_none/1, map/2, map_error/2, flatten/1,
    flat_map/2, unwrap/2, to_maybe/1, from_maybe/1

import Maybe exposing Maybe(..)

doc """
Result represents the result of something that may succeed or fail.
`Ok` means it was successful, `Error` means it failed.
"""
type Result(error, value) {
  | Ok(value)
  | Error(error)

; // Fix GitHub syntax highlighting

fn is_ok(result) {
  case result {
  | Error(_) => False
  | Ok(_) => True
  }
}

test is_ok {
  is_ok(Ok(1)) |> Assert.true
  is_ok(Error(1)) |> Assert.false
}

fn is_error(result) {
  case result {
  | Ok(_) => False
  | Error(_) => True
  }
}

test is_error {
  is_error(Ok(1)) |> Assert.false
  is_error(Error(1)) |> Assert.true
}

fn map(result, fun) {
  case result {
  | Ok(x) => fun(x)
  | Error(_) => result
  }
}

test map {
  map(Ok(1), |x| x + 1) |> Assert.equal(_, Ok(2))
  map(Error(1), |x| x + 1) |> Assert.equal(Error(1))
}

fn map_error(result, fun) {
  case result {
  | Ok(_) => result
  | Error(error) => error |> fun |> Error
  }
}

test map_error {
  map_error(Ok(1), |x| x + 1) |> Assert.equal(_, Ok(1))
  map_error(Error(1), |x| x + 1) |> Assert.equal(Error(2))
}

fn flatten(result) {
  case result {
  | Ok(x) => x
  | Error(_) => result
  }
}

test flatten {
  flatten(Ok(Ok(1))) |> Assert.equal(_, Ok(1))
  flatten(Ok(Error(1))) |> Assert.equal(_, Error(1))
  flatten(Error(1)) |> Assert.equal(_, Error(1))
}

fn flat_map(result, fun) {
  result
    |> unwrap(_, fun)
    |> flatten
}

test flat_map {
  flat_map(Error(1), |x| Ok(x + 1)) |> Assert.equal(_, Error(1))
  flat_map(Ok(1), |x| Ok(x + 1)) |> Assert.equal(_, Ok(2))
  flat_map(Ok(1), |_| Error(1)) |> Assert.equal(_, Error(1))
}

fn unwrap(result, default) {
  case result {
  | Ok(v) => v
  | Error(_) => default
  }
}

test unwrap {
  unwrap(Ok(1), 50) |> Assert.equal(_, 1)
  unwrap(Error("nope"), 50) |> Assert.equal(_, 50)
}

fn to_maybe(result) {
  case result {
  | Ok(v) => Just(v)
  | Error(_) => Nothing
  }
}

test to_maybe {
  to_maybe(Ok(1)) |> Assert.equal(_, Just(_, 1))
  to_maybe(Error(1)) |> Assert.equal(_, Nothing)
}

fn from_maybe(maybe, error_reason) {
  case maybe {
  | Just(v) => Ok(v)
  | Nothing => Error(error_reason)
  }
}

test from_maybe {
  to_maybe(Just(1), :ok) |> Assert.equal(_, Ok(1))
  to_maybe(Nothing, :ok) |> Assert.equal(_, Error(:ok))
}