diff options
author | Louis Pilfold <louis@lpil.uk> | 2019-03-23 10:58:52 +0000 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2019-03-23 10:58:52 +0000 |
commit | 27fec2149c765de657d45382af91c361eb3c953c (patch) | |
tree | 2736c4e1320c7f6b144071b2a11e10df598982ce /gen/list.erl | |
parent | 6af3f431609b2c530ae3f8598ac16815e26748d2 (diff) | |
download | gleam_stdlib-27fec2149c765de657d45382af91c361eb3c953c.tar.gz gleam_stdlib-27fec2149c765de657d45382af91c361eb3c953c.zip |
stdlib additions
Diffstat (limited to 'gen/list.erl')
-rw-r--r-- | gen/list.erl | 31 |
1 files changed, 30 insertions, 1 deletions
diff --git a/gen/list.erl b/gen/list.erl index a5df23e..1567b98 100644 --- a/gen/list.erl +++ b/gen/list.erl @@ -2,7 +2,7 @@ -compile(no_auto_import). -include_lib("eunit/include/eunit.hrl"). --export([length/1, reverse/1, is_empty/1, has_member/2, head/1, tail/1, filter/2, map/2, traverse/2, drop/2, take/2, new/0, append/2, flatten/1, foldl/3, foldr/3]). +-export([length/1, reverse/1, is_empty/1, has_member/2, head/1, tail/1, filter/2, map/2, traverse/2, drop/2, take/2, new/0, append/2, flatten/1, foldl/3, foldr/3, find/2]). length(A) -> erlang:length(A). @@ -264,3 +264,32 @@ foldr(List, Acc, Fun) -> foldr_test() -> expect:equal(foldr([1, 2, 3], [], fun(X, Acc) -> [X | Acc] end), [1, 2, 3]). -endif. + +find(Haystack, F) -> + case Haystack of + [] -> + {error, not_found}; + + [X | Rest] -> + case F(X) of + {ok, X1} -> + {ok, X1}; + + _ -> + find(Rest, F) + end + end. + +-ifdef(TEST). +find_test() -> + F = fun(X) -> case X of + 2 -> + {ok, 4}; + + _ -> + {error, not_found} + end end, + expect:equal(find([1, 2, 3], F), {ok, 4}), + expect:equal(find([1, 3, 2], F), {ok, 4}), + expect:equal(find([1, 3], F), {error, not_found}). +-endif. |