Skip to content

Commit bed7051

Browse files
committed
feat(std): add utility functions to Option and Result
1 parent 7eae498 commit bed7051

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

std/option.glu

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,16 @@ let unwrap opt : Option a -> a =
2323
| Some x -> x
2424
| None -> error "Option was None"
2525

26+
let unwrap_or default opt : a -> Option a -> a =
27+
match opt with
28+
| Some x -> x
29+
| None -> default
30+
31+
let to_result err opt : e -> Option a -> Result e a =
32+
match opt with
33+
| Some x -> Ok x
34+
| None -> Err err
35+
2636
let former =
2737
let semigroup : Semigroup (Option a) = {
2838
append = \l r ->
@@ -148,7 +158,11 @@ let traversable : Traversable Option = {
148158

149159
{
150160
Option,
161+
151162
unwrap,
163+
unwrap_or,
164+
to_result,
165+
152166
semigroup,
153167
monoid,
154168
former,

std/result.glu

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,16 +20,31 @@ let unwrap_ok res : Result e a -> a =
2020
| Ok x -> x
2121
| Err _ -> error "Result was an Err"
2222

23+
let unwrap_ok_or default res : a -> Result e a -> a =
24+
match res with
25+
| Ok x -> x
26+
| Err _ -> default
27+
2328
let unwrap_err res : Result e a -> e =
2429
match res with
2530
| Ok _ -> error "Result was an Ok"
2631
| Err x -> x
2732

33+
let unwrap_err_or default res : e -> Result e a -> e =
34+
match res with
35+
| Ok _ -> default
36+
| Err x -> x
37+
2838
let map_err f res : (e -> f) -> Result e a -> Result f a =
2939
match res with
3040
| Ok a -> Ok a
3141
| Err e -> Err (f e)
3242

43+
let to_option res : Result e a -> Option a =
44+
match res with
45+
| Ok x -> Some x
46+
| Err _ -> None
47+
3348
let eq : [Eq e] -> [Eq a] -> Eq (Result e a) = {
3449
(==) = \l r ->
3550
match (l, r) with
@@ -103,9 +118,14 @@ let show ?e ?t : [Show e] -> [Show t] -> Show (Result e t) =
103118

104119
{
105120
Result,
121+
106122
unwrap_ok,
123+
unwrap_ok_or,
107124
unwrap_err,
125+
unwrap_err_or,
108126
map_err,
127+
to_option,
128+
109129
eq,
110130
ord,
111131
functor,

0 commit comments

Comments
 (0)