forked from functionaljava/functionaljava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReader.java
More file actions
50 lines (37 loc) · 946 Bytes
/
Reader.java
File metadata and controls
50 lines (37 loc) · 946 Bytes
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
39
40
41
42
43
44
45
46
47
48
49
50
package fj.data;
import fj.F;
import fj.F1Functions;
/**
* The Reader monad (also called the function monad, so equivalent to the idea of F).
* Created by MarkPerry on 7/07/2014.
*/
public class Reader<A, B> {
private final F<A, B> function;
public Reader(F<A, B> f) {
function = f;
}
public final F<A, B> getFunction() {
return function;
}
public static <A, B> Reader<A, B> unit(F<A, B> f) {
return new Reader<>(f);
}
public static <A, B> Reader<A, B> constant(B b) {
return unit(a -> b);
}
public final B f(A a) {
return function.f(a);
}
public final <C> Reader<A, C> map(F<B, C> f) {
return unit(F1Functions.andThen(function, f));
}
public final <C> Reader<A, C> andThen(F<B, C> f) {
return map(f);
}
public final <C> Reader<A, C> flatMap(F<B, Reader<A, C>> f) {
return unit(a -> f.f(function.f(a)).f(a));
}
public final <C> Reader<A, C> bind(F<B, Reader<A, C>> f) {
return flatMap(f);
}
}