1
1
open Functor ;;
2
2
3
- (* Let's define an OCaml functor that `fmap`s n -> n + 1 *)
4
- module Increment (F : Functor ) = struct
5
- let go = F. fmap ((+ ) 1 )
6
- end
7
-
8
3
(* Define a Maybe functor *)
9
- module Maybe = struct
4
+ module Maybe : ( Functor with type 'a t = 'a option ) = struct
10
5
type 'a t = 'a option
11
6
let fmap f x = match x with
12
7
| Some v -> Some (f v)
13
8
| None -> None
14
9
end
15
10
16
- (* Let's increment some Maybes *)
17
- module IncrementMaybe = Increment (Maybe )
18
-
19
11
let get_age = function
20
12
| "Jordan" -> Some 25
21
13
| "Steve" -> Some 29
22
14
| "Jake" -> Some 1
23
15
| _ -> None
24
16
25
- let age_next_year = IncrementMaybe. go
17
+ let age_next_year = Maybe. fmap (( + ) 1 )
26
18
27
19
let string_of_age = function
28
20
| None -> " User not found"
@@ -33,9 +25,8 @@ assert(get_age "Jake" |> age_next_year |> string_of_age = "2");;
33
25
assert (get_age " Melissa" |> age_next_year |> string_of_age = " User not found" );;
34
26
35
27
(* Let's increment some Stacks! Which are also Functors *)
36
- module IncrementStack = Increment (Mystack )
37
28
let stack = Mystack. stack_of_list [3 ; 5 ; 1 ; 2 ];;
38
- assert (IncrementStack. go stack |> Mystack. list_of_stack = [4 ; 6 ; 2 ; 3 ]);;
29
+ assert (Mystack. fmap (( + ) 1 ) stack |> Mystack. list_of_stack = [4 ; 6 ; 2 ; 3 ]);;
39
30
40
31
(* An either module *)
41
32
module Either (Config : sig type t end ) = struct
47
38
48
39
(* Why can't I combine these two lines? *)
49
40
module EitherString = Either (struct type t = string end )
50
- module IncrementEither = Increment (EitherString )
51
41
52
42
let get_age_either = function
53
43
| "Jordan" -> EitherString. Right 25
54
44
| "Steve" -> EitherString. Right 29
55
45
| "Jake" -> EitherString. Right 1
56
46
| _ -> EitherString. Left " User not found :("
57
47
58
- let age_next_year_either = IncrementEither. go
48
+ let age_next_year_either = EitherString. fmap (( + ) 1 )
59
49
60
50
let string_of_age_either = function
61
51
| EitherString. Left e -> e
0 commit comments