Skip to content

Commit 27e16c9

Browse files
committed
simply Functor usage
1 parent 30c2911 commit 27e16c9

File tree

1 file changed

+4
-14
lines changed

1 file changed

+4
-14
lines changed

src/functor_test.ml

+4-14
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,20 @@
11
open Functor;;
22

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-
83
(* Define a Maybe functor *)
9-
module Maybe = struct
4+
module Maybe : (Functor with type 'a t = 'a option) = struct
105
type 'a t = 'a option
116
let fmap f x = match x with
127
| Some v -> Some (f v)
138
| None -> None
149
end
1510

16-
(* Let's increment some Maybes *)
17-
module IncrementMaybe = Increment (Maybe)
18-
1911
let get_age = function
2012
| "Jordan" -> Some 25
2113
| "Steve" -> Some 29
2214
| "Jake" -> Some 1
2315
| _ -> None
2416

25-
let age_next_year = IncrementMaybe.go
17+
let age_next_year = Maybe.fmap ((+) 1)
2618

2719
let string_of_age = function
2820
| None -> "User not found"
@@ -33,9 +25,8 @@ assert(get_age "Jake" |> age_next_year |> string_of_age = "2");;
3325
assert(get_age "Melissa" |> age_next_year |> string_of_age = "User not found");;
3426

3527
(* Let's increment some Stacks! Which are also Functors *)
36-
module IncrementStack = Increment (Mystack)
3728
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]);;
3930

4031
(* An either module *)
4132
module Either (Config: sig type t end) = struct
@@ -47,15 +38,14 @@ end
4738

4839
(* Why can't I combine these two lines? *)
4940
module EitherString = Either (struct type t = string end)
50-
module IncrementEither = Increment (EitherString)
5141

5242
let get_age_either = function
5343
| "Jordan" -> EitherString.Right 25
5444
| "Steve" -> EitherString.Right 29
5545
| "Jake" -> EitherString.Right 1
5646
| _ -> EitherString.Left "User not found :("
5747

58-
let age_next_year_either = IncrementEither.go
48+
let age_next_year_either = EitherString.fmap ((+) 1)
5949

6050
let string_of_age_either = function
6151
| EitherString.Left e -> e

0 commit comments

Comments
 (0)