Last active
November 16, 2016 00:25
-
-
Save sn1p3r46/a5bf5953c264d6d79ac3a39996cfff23 to your computer and use it in GitHub Desktop.
Erlang functional programming exercises;
This file contains 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
%%% Exercises description on comments; | |
-module(exercises0). | |
-export([count/1,repeated_elems/1,most_frequent_elem/1,ntimes/3]). | |
%%% #1 | |
count([H|T]) -> | |
count([H|T],[]); | |
count([]) -> []. | |
count([],L) -> L; | |
count([H|T],L) -> | |
count(T,count(H,L,[])). | |
count(V,[ {C,K} | T ],L) -> | |
case K of | |
V -> L ++ [{C+1,K} | T]; | |
_ -> count(V,T,L ++ [{C,K}]) | |
end; | |
count(V,[],L) -> L ++ [{1,V}]. | |
%%% #2 | |
most_frequent_elem([H|T]) -> | |
most_frequent_elem(count([H|T]),{0,0}). | |
most_frequent_elem([{C0,K0}|T],{C,K}) -> | |
case (C0>=C) of | |
true -> most_frequent_elem(T,{C0,K0}); | |
false -> most_frequent_elem(T,{C,K}) | |
end; | |
most_frequent_elem([],{_,K})->K. | |
%%% #3 | |
repeated_elems([H|T]) -> | |
[ K || {C,K} <- count([H|T]) , C>1]. | |
%%% #4 | |
ntimes(F,N,EList) -> | |
[ asd(F,N,V) || V <- EList ]. | |
asd(_,0,R) -> R; | |
asd(F,N,R) -> | |
asd(F,N-1,F(R)). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Exercises0
#1 Count function
Define the count function that finds all repeated elements in a list and packs them together with the number of their occurrences as pairs.
Test cases:
#2 Most frequent elements
Define the
most_frequent_elem/1
function that returns which element occurs the most in a list.Test cases:
#3 Repeated elements
Define the
repeated_elems/1
function that determines what elements occur more than once in a list.Test cases:
#4 Applying a function n times
Define the
ntimes/3
function that applies theF
function on each element of the given listN
times.If you have to apply function
f/1
3 times and EList is[1,2]
, then the return value of the function defined as:[f(f(f(1))), f(f(f(2)))]
Andrea Galloni