Skip to content

Instantly share code, notes, and snippets.

@Joakineee
Created May 15, 2020 12:47
Show Gist options
  • Save Joakineee/fafda1c11c8f025891128c75840f9de5 to your computer and use it in GitHub Desktop.
Save Joakineee/fafda1c11c8f025891128c75840f9de5 to your computer and use it in GitHub Desktop.
Erlang exercise nub
-module(nub).
-export([test/0,nub/1]).
-spec nub(list()) -> list().
nub(L) -> nub(L,[]).
%Adds non repeated elements to the list.
-spec nub(list(),list()) -> list().
nub([],Acc) ->
lists:reverse(Acc);
nub([H|T],Acc) ->
case inlist(H,Acc) of
true -> nub(T,Acc);
false -> nub(T,[H|Acc])
end.
%returns true if the element is already in list.
-spec inlist(integer(),list()) -> boolean().
inlist(_,[]) -> false;
inlist(X,[X|_]) -> true;
inlist(X,[_|T]) -> inlist(X,T).
test() ->
[1,2,3,43,435] = nub:nub([1,2,3,43,435,2,2,2,2]),
ok.
@Joakineee
Copy link
Author

Oh okay, I didn't understand the difference betwen list() and [T], now i do.
Thanks again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment