Last active
May 12, 2017 14:19
-
-
Save rpt/e069ab294e7dac9de247 to your computer and use it in GitHub Desktop.
Partial function in Erlang, who would have thought?...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(partial). | |
-export([partial/2]). | |
-export([test/0]). | |
-spec partial(function(), [term()]) -> function(). | |
partial(Fun, Args) when is_function(Fun), is_list(Args) -> | |
lists:foldl(fun partial1/2, Fun, Args). | |
-spec partial1(term(), function()) -> function(). | |
partial1(A, Fun) when is_function(Fun, 1) -> | |
fun() -> Fun(A) end; | |
partial1(A, Fun) when is_function(Fun, 2) -> | |
fun(B) -> Fun(A, B) end; | |
partial1(A, Fun) when is_function(Fun, 3) -> | |
fun(B, C) -> Fun(A, B, C) end; | |
partial1(A, Fun) when is_function(Fun, 4) -> | |
fun(B, C, D) -> Fun(A, B, C, D) end; | |
partial1(A, Fun) when is_function(Fun, 5) -> | |
fun(B, C, D, E) -> Fun(A, B, C, D, E) end; | |
partial1(A, Fun) when is_function(Fun, 6) -> | |
fun(B, C, D, E, F) -> Fun(A, B, C, D, E, F) end; | |
partial1(A, Fun) when is_function(Fun, 7) -> | |
fun(B, C, D, E, F, G) -> Fun(A, B, C, D, E, F, G) end; | |
partial1(A, Fun) when is_function(Fun, 8) -> | |
fun(B, C, D, E, F, G, H) -> Fun(A, B, C, D, E, F, G, H) end; | |
partial1(A, Fun) when is_function(Fun, 9) -> | |
fun(B, C, D, E, F, G, H, I) -> Fun(A, B, C, D, E, F, G, H, I) end; | |
partial1(A, Fun) when is_function(Fun, 10) -> | |
fun(B, C, D, E, F, G, H, I, J) -> Fun(A, B, C, D, E, F, G, H, I, J) end; | |
partial1(A, Fun) when is_function(Fun, 11) -> | |
fun(B, C, D, E, F, G, H, I, J, K) -> | |
Fun(A, B, C, D, E, F, G, H, I, J, K) | |
end; | |
partial1(A, Fun) when is_function(Fun, 12) -> | |
fun(B, C, D, E, F, G, H, I, J, K, L) -> | |
Fun(A, B, C, D, E, F, G, H, I, J, K, L) | |
end. | |
test() -> | |
F = partial:partial(fun lists:map/2, [fun(X) -> X + 1 end]), | |
[2,3,4] = F([1,2,3]), | |
passed. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment