Skip to content

Commit fe3ccd6

Browse files
committed
basic result type and functions
1 parent f7b71df commit fe3ccd6

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

.gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
.rebar3
2+
_build
3+
_checkouts

src/result.alp

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
{- Basic result type.
2+
-}
3+
module result
4+
5+
import_type option.option
6+
7+
export isOk/1, map/1, fromOption/2, andThen/2, withDefault/2
8+
9+
export_type result
10+
11+
type result 'a 'b = Ok 'a | Err 'b
12+
13+
let isOk r =
14+
match r with
15+
Ok _ -> true
16+
| Err _ -> false
17+
18+
test "Applying `is_ok` to Ok x should return true" =
19+
assert.equal (true) (is_ok (Ok 1))
20+
21+
let map f (Ok x) = Ok (f x)
22+
23+
let map _ (Err x) = Err x
24+
25+
test "mapping the identity function to Ok x should return Ok x" =
26+
let f x = x in
27+
assert.equal (Ok 1) (map f (Ok 1))
28+
29+
let fromOption opt e =
30+
match opt with
31+
Some x -> Ok x
32+
| None -> Err e
33+
34+
let andThen callback (Ok value) = callback value
35+
let andThen _ (Err msg) = Err msg
36+
37+
test "andThen test with Ok x" =
38+
let f x = (Ok x) in
39+
assert.equal (Ok 1) (andThen f (Ok 1))
40+
41+
test "andThen with Err x and identity function is Err x" =
42+
let f x = (Ok x) in
43+
assert.equal (Err "msg") (andThen f (Err "msg"))
44+
45+
let withDefault _ (Ok x) = x
46+
let withDefault default (Err _) = default
47+
48+
test "withdefault test with Ok result" =
49+
let f x = (Ok x) in
50+
assert.equal (1) (withDefault 0 (f 1))
51+
52+
test "withdefault test with Err returning default" =
53+
let f _ = (Err "error") in
54+
assert.equal (0) (withDefault 0 (f 1))

0 commit comments

Comments
 (0)