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 | |
64617423 SK |
9 | ]). |
10 | ||
11 | -spec id(A) -> | |
12 | A. | |
13 | id(X) -> | |
14 | X. | |
e033aade SK |
15 | |
16 | -spec curry(fun()) -> | |
17 | fun(). | |
18 | curry(F) -> | |
a3173cf2 | 19 | {arity, Arity} = erlang:fun_info(F, arity), |
e033aade SK |
20 | curry(F, [], Arity). |
21 | ||
22 | -spec curry(fun(), list(), integer()) -> | |
23 | fun(). | |
24 | curry(F, Args, 0) -> | |
25 | apply(F, lists:reverse(Args)); | |
26 | curry(F, Args, Arity) -> | |
27 | fun (X) -> curry(F, [X | Args], Arity - 1) end. | |
0b6ed617 SK |
28 | |
29 | -spec compose([fun((A) -> B)]) -> | |
30 | fun((A) -> B). | |
31 | compose(Fs) -> | |
32 | compose_right(Fs). | |
33 | ||
34 | -spec compose_right([fun((A) -> B)]) -> | |
35 | fun((A) -> B). | |
36 | compose_right(Fs) -> | |
37 | compose_given_fold(Fs, fun lists:foldr/3). | |
38 | ||
39 | -spec compose_left([fun((A) -> B)]) -> | |
40 | fun((A) -> B). | |
41 | compose_left(Fs) -> | |
42 | compose_given_fold(Fs, fun lists:foldl/3). | |
43 | ||
44 | ||
45 | %% ============================================================================ | |
46 | ||
47 | -spec compose_given_fold([fun((A) -> B)], fun((fun((A, B) -> C), B, [A]) -> C)) -> | |
48 | fun((A) -> C). | |
49 | compose_given_fold(Fs, Fold) -> | |
50 | fun (X) -> Fold(fun (F, Y) -> F(Y) end, X, Fs) end. |