Created
June 28, 2017 16:11
-
-
Save andreburgaud/d3cae0a518345b3aaf5faae4fbb0cfc2 to your computer and use it in GitHub Desktop.
FutureLearn - Functional Programming in Erlang 2.12 - The 'nub' function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(nub). | |
-export([all_tests/0,nub/1,nub2/1]). | |
%% Helper to add element to list with no duplicate elements. | |
add(X, []) -> [X]; | |
add(X, [Y|Uniqs]) when X == Y -> [Y|Uniqs]; | |
add(X, [Y|Uniqs]) -> [Y|add(X, Uniqs)]. | |
%% Helper to create a list of unique elements. | |
uniqs([],Uniqs) -> Uniqs; | |
uniqs([X|Xs],Uniqs) -> | |
uniqs(Xs,add(X,Uniqs)). | |
%% Reverse a list. | |
-spec reverse([T]) -> [T]. | |
reverse(Xs) -> reverse(Xs, []). | |
-spec reverse([T], [T]) -> [T]. | |
reverse([], Ys) -> Ys; | |
reverse([X|Xs], Ys) -> reverse(Xs, [X|Ys]). | |
%% Removes all duplications from a list (keeping the first occurence) | |
-spec nub([T]) -> [T]. | |
nub([]) -> []; | |
nub(Xs) -> uniqs(Xs,[]). | |
%% Removes all duplications from a list (keeping the last occurence) | |
-spec nub2([T]) -> [T]. | |
nub2([]) -> []; | |
nub2(Xs) -> reverse(uniqs(reverse(Xs),[])). | |
all_tests() -> | |
[2,4,1,3] = nub([2,4,1,3,3,1]), | |
[2,4,3,1] = nub2([2,4,1,3,3,1]), | |
success. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment