Skip to content

Instantly share code, notes, and snippets.

@izinin
Created April 8, 2016 08:15
Show Gist options
  • Save izinin/9d91ebc9dcb0294f4770a21a05845c25 to your computer and use it in GitHub Desktop.
Save izinin/9d91ebc9dcb0294f4770a21a05845c25 to your computer and use it in GitHub Desktop.
Erlang: replacing 'null' value with specified replacement in hieracy list tree
%% @doc replaces 'null' value with specified replacement in hieracy list tree
%% list elements can contain tuples
-spec replace_null(Replacement :: term(), InputTree :: list(), Accumulator :: list()) -> Result when
Result :: list().
%% --------------------------------------------------------
%% manual testing :
%% > R = [[<<"username">>,<<"jid">>,<<"nick">>,<<"last">>,
%% <<"subscription">>,<<"ask">>,<<"askmessage">>,<<"server">>,
%% <<"subscribe">>,<<"type">>],
%% [{<<"XXXXXXXXXXX">>,<<"AAAAAAAAAAA@im.domain.im">>,<<" ">>,
%% <<"ZZZZZZZZZZZ">>,<<"B">>,<<"N">>,<<" ">>,<<"N">>,null,
%% <<"item">>},
%% {<<"XXXXXXXXXXX">>,<<"BBBBBBBBBBB@im.domain.im">>,null,
%% <<"CCCCCCCCCC">>,<<"B">>,<<"N">>,<<" ">>,<<"N">>,null,
%% <<"item">>}]].
%% > utility:replace_null(null, R, []) == R.
%% true <-- the test result
%% --------------------------------------------------------
replace_null(_, [], A) -> lists:reverse(A);
replace_null(R, [ null | T ], A) -> replace_null(R, T, [R | A]);
replace_null(Replacement, [H | T], A) when is_tuple(H) ->
R = replace_null(Replacement, tuple_to_list(H), []),
replace_null(Replacement, T, [list_to_tuple(R) | A]);
replace_null(Replacement, [H | T], A) when is_list(H) ->
R = replace_null(Replacement, H, []),
replace_null(Replacement, T, [R | A]);
replace_null(R, [H | T], A) when is_binary(H) -> replace_null(R, T, [H | A]);
replace_null(_, _, A) -> A.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment