| 1 |
|
-module(klsn_maybe). |
| 2 |
|
|
| 3 |
|
-export([ |
| 4 |
|
get_value/1 |
| 5 |
|
, get_value/2 |
| 6 |
|
, has_value/1 |
| 7 |
|
, filtermap/2 |
| 8 |
|
]). |
| 9 |
|
|
| 10 |
|
%% A small helper module for working with the *Maybe* pattern |
| 11 |
|
%% ({value, V} | none) that is defined in the klsn module itself. The functions |
| 12 |
|
%% mirror common operations from the Haskell Maybe / Rust Option |
| 13 |
|
%% family while keeping the interface idiomatic Erlang. |
| 14 |
|
|
| 15 |
|
-export_type([ |
| 16 |
|
]). |
| 17 |
|
|
| 18 |
|
%% @doc |
| 19 |
|
%% Return true when a Maybe contains a value, otherwise false. |
| 20 |
|
-spec has_value(klsn:'maybe'(any())) -> boolean(). |
| 21 |
|
has_value({value, _}) -> |
| 22 |
:-( |
true; |
| 23 |
|
has_value(none) -> |
| 24 |
:-( |
false; |
| 25 |
|
has_value(Arg1) -> |
| 26 |
:-( |
erlang:error(badarg, [Arg1]). |
| 27 |
|
|
| 28 |
|
%% @doc |
| 29 |
|
%% Extract the wrapped value or raise badarg when *None* is supplied. |
| 30 |
|
-spec get_value({value, Value}) -> Value. |
| 31 |
|
get_value({value, Value}) -> |
| 32 |
:-( |
Value; |
| 33 |
|
get_value(None) -> |
| 34 |
:-( |
erlang:error(badarg, [None]). |
| 35 |
|
|
| 36 |
|
%% @doc |
| 37 |
|
%% Return the contained value when present, otherwise return *Default*. |
| 38 |
|
-spec get_value |
| 39 |
|
({value, Value}, Default::any()) -> Value; |
| 40 |
|
(none, Default) -> Default. |
| 41 |
|
get_value({value, Value}, _Default) -> |
| 42 |
:-( |
Value; |
| 43 |
|
get_value(none, Default) -> |
| 44 |
:-( |
Default; |
| 45 |
|
get_value(Arg1, Arg2) -> |
| 46 |
:-( |
erlang:error(badarg, [Arg1, Arg2]). |
| 47 |
|
|
| 48 |
|
|
| 49 |
|
%% @doc |
| 50 |
|
%% Combine filtering and mapping in one pass. When the callback returns |
| 51 |
|
%% {value, V} the element is kept (and V becomes the new value); |
| 52 |
|
%% returning none discards the element. |
| 53 |
|
-spec filtermap(fun((any())->klsn:'maybe'(any())), list()) -> list(); |
| 54 |
|
(fun((any(), any())->klsn:'maybe'(any())), map()) -> map(). |
| 55 |
|
filtermap(Fun, List) when is_list(List) -> |
| 56 |
:-( |
lists:filtermap(fun(Val) -> |
| 57 |
:-( |
case Fun(Val) of |
| 58 |
|
{value, Value} -> |
| 59 |
:-( |
{true, Value}; |
| 60 |
|
none -> |
| 61 |
:-( |
false |
| 62 |
|
end |
| 63 |
|
end, List); |
| 64 |
|
filtermap(Fun, Map) when is_map(Map) -> |
| 65 |
:-( |
maps:filtermap(fun(Key, Val) -> |
| 66 |
:-( |
case Fun(Key, Val) of |
| 67 |
|
{value, Value} -> |
| 68 |
:-( |
{true, Value}; |
| 69 |
|
none -> |
| 70 |
:-( |
false |
| 71 |
|
end |
| 72 |
|
end, Map). |