-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheither.zp
38 lines (30 loc) · 1.5 KB
/
either.zp
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
(load "monads/monads.zp")
(define (monads:left err) "build a left instance of the either monad"
(monads:generic err :left (lambda (val) (monads:left val)) (lambda (f) (monads:left err))))
(define (monads:right val) "build a right instance of the either monad"
(monads:generic val :right (lambda (val) (monads:right val)) (lambda (f) (f val))))
(define (monads:left? monad) "is monad instance left?"
(eq? (monads:get-type monad) :left))
(define (monads:right? monad) "is monad instance right?"
(eq? (monads:get-type monad) :right))
(define (monads:partition-eithers monads)
"returns a list of two lists, the first being the left values, the second being the right ones"
(list (monads:lefts monads) (monads:rights monads)))
(define (monads:lefts monads)
"returns all the left elements in the list"
(filter monads:left? monads))
(define (monads:rights monads)
"returns all the right elements in the list"
(filter monads:right? monads))
(define-syntax monads:either
(syntax-rules (=>)
((monads:either monad (x => r) (y => l))
(if (monads:right? monad)
(let ((x (monads:get-val! monad)))
r)
(let ((y (monads:get-val! monad)))
l)))
((monads:either x)
(error "Syntax error in call to monads:either, called with:" 'x ";\ncorrect form is (monad (var => on-right) (err-var => on-left))"))
((monads:either x ...)
(error "Syntax error in call to monads:either, called with:" 'x ";\ncorrect form is (monad (var => on-right) (err-var => on-left))"))))