Commit | Line | Data |
---|---|---|
64617423 SK |
1 | -module(hope_fun). |
2 | ||
3 | -export( | |
4 | [ id/1 | |
e033aade | 5 | , curry/1 |
0b6ed617 SK |
6 | , compose/1 % alias for compose_right/1 |
7 | , compose_right/1 | |
8 | , compose_left/1 | |
cb14ad76 | 9 | , thread/2 |
64617423 SK |
10 | ]). |
11 | ||
12 | -spec id(A) -> | |
13 | A. | |
14 | id(X) -> | |
15 | X. | |
e033aade SK |
16 | |
17 | -spec curry(fun()) -> | |
18 | fun(). | |
19 | curry(F) -> | |
a3173cf2 | 20 | {arity, Arity} = erlang:fun_info(F, arity), |
e033aade SK |
21 | curry(F, [], Arity). |
22 | ||
23 | -spec curry(fun(), list(), integer()) -> | |
24 | fun(). | |
25 | curry(F, Args, 0) -> | |
26 | apply(F, lists:reverse(Args)); | |
27 | curry(F, Args, Arity) -> | |
28 | fun (X) -> curry(F, [X | Args], Arity - 1) end. | |
0b6ed617 SK |
29 | |
30 | -spec compose([fun((A) -> B)]) -> | |
31 | fun((A) -> B). | |
32 | compose(Fs) -> | |
33 | compose_right(Fs). | |
34 | ||
35 | -spec compose_right([fun((A) -> B)]) -> | |
36 | fun((A) -> B). | |
37 | compose_right(Fs) -> | |
38 | compose_given_fold(Fs, fun lists:foldr/3). | |
39 | ||
40 | -spec compose_left([fun((A) -> B)]) -> | |
41 | fun((A) -> B). | |
42 | compose_left(Fs) -> | |
43 | compose_given_fold(Fs, fun lists:foldl/3). | |
44 | ||
cb14ad76 SK |
45 | -spec thread([fun((A) -> B)], A) -> |
46 | B. | |
47 | thread(Fs, X) -> | |
48 | F = compose_left(Fs), | |
49 | F(X). | |
50 | ||
0b6ed617 SK |
51 | |
52 | %% ============================================================================ | |
53 | ||
54 | -spec compose_given_fold([fun((A) -> B)], fun((fun((A, B) -> C), B, [A]) -> C)) -> | |
55 | fun((A) -> C). | |
56 | compose_given_fold(Fs, Fold) -> | |
57 | fun (X) -> Fold(fun (F, Y) -> F(Y) end, X, Fs) end. |