diff options
Diffstat (limited to 'gen')
-rw-r--r-- | gen/src/gleam@generic.erl | 16 | ||||
-rw-r--r-- | gen/test/gleam@generic_test.erl | 44 |
2 files changed, 60 insertions, 0 deletions
diff --git a/gen/src/gleam@generic.erl b/gen/src/gleam@generic.erl new file mode 100644 index 0000000..a25a59f --- /dev/null +++ b/gen/src/gleam@generic.erl @@ -0,0 +1,16 @@ +-module(gleam@generic). +-compile(no_auto_import). + +-export([identity/1, always/2, flip/1, compose/2]). + +identity(A) -> + A. + +always(_, B) -> + B. + +flip(Fun) -> + fun(B, A) -> Fun(A, B) end. + +compose(Fun1, Fun2) -> + fun(A) -> Fun2(Fun1(A)) end. diff --git a/gen/test/gleam@generic_test.erl b/gen/test/gleam@generic_test.erl new file mode 100644 index 0000000..eecf650 --- /dev/null +++ b/gen/test/gleam@generic_test.erl @@ -0,0 +1,44 @@ +-module(gleam@generic_test). +-compile(no_auto_import). + +-export([identity_test/0, always_test/0, flip_test/0, compose_test/0]). + +identity_test() -> + gleam@expect:equal(gleam@generic:identity(1), 1). + +always_test() -> + gleam@expect:equal(gleam@generic:always(1, 2), 2). + +flip_test() -> + Fun = fun(String, Int) -> + gleam@string:append( + gleam@string:append( + gleam@string:append( + gleam@string:append(<<"String: '">>, String), + <<"', Int: '">> + ), + gleam@int:to_string(Int) + ), + <<"'">> + ) + end, + FlippedFun = gleam@generic:flip(Fun), + gleam@expect:equal(Fun(<<"Bob">>, 1), <<"String: 'Bob', Int: '1'">>), + gleam@expect:equal( + FlippedFun(2, <<"Alice">>), + <<"String: 'Alice', Int: '2'">> + ). + +compose_test() -> + AddTwo = fun(Int) -> Int + 2 end, + AddThree = fun(Int1) -> Int1 + 3 end, + AddFive = gleam@generic:compose(AddTwo, AddThree), + gleam@expect:equal(AddFive(1), 6), + HeadToString = gleam@generic:compose( + fun gleam@list:head/1, + fun(IntResult) -> + gleam@int:to_string(gleam@result:unwrap(IntResult, 0)) + end + ), + gleam@expect:equal(HeadToString([1]), <<"1">>), + gleam@expect:equal(HeadToString([]), <<"0">>). |