Created
March 14, 2017 21:35
-
-
Save paucus/4a4985e5b82da96b01441a0b0490e5e2 to your computer and use it in GitHub Desktop.
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(a35). | |
| -export([doubleAll/1, evens/1, product/1,zip/2,zip_with/3,zip_with_map/3,zip_with_zip_with/2]). | |
| -include_lib("eunit/include/eunit.hrl"). | |
| -created_by("Marcelo Ruiz Camauër"). | |
| %%% invoke with: | |
| %%% a35:test(). | |
| %%% higher order functions | |
| %%% Define the functions doubleAll, evens, and product using the higher-order | |
| %%% functions lists:map, lists:filter and lists:foldr. | |
| %doubleAll([]) -> []; | |
| %doubleAll([X|Xs]) -> | |
| % [ 2*X | doubleAll(Xs) ]. | |
| doubleAll(L) -> | |
| lists:map(fun(X) -> 2*X end,L). | |
| doubleAll_test()-> | |
| ?assertEqual([2,4,6],doubleAll([1,2,3])), | |
| ok. | |
| %evens([]) -> []; | |
| %evens([X|Xs]) when X rem 2 == 0 -> | |
| % [X | evens(Xs) ]; | |
| %evens([_|Xs]) -> | |
| % evens(Xs). | |
| evens(L) -> lists:filter(fun(Y) -> Y rem 2 =:= 0 end, L). | |
| evens_test()-> | |
| ?assertEqual([2,4],evens([2,3,4,5])), | |
| ok. | |
| %product([]) -> 1; | |
| %product([X|Xs]) -> X * product(Xs). | |
| product(L)->lists:foldr(fun(X,Partial) -> X * Partial end,1,L). | |
| product_test()-> | |
| ?assertEqual(120,product([2,3,4,5])), | |
| ok. | |
| % Zipping | |
| % a) Define a function zip/2 that “zips together” pairs of elements from two lists like this: | |
| % | |
| % zip([1,3,5,7], [2,4]) = [ {1,2}, {3,4} ] | |
| % where you can see that the elements from the longer list are lost. | |
| zip(_,[]) -> []; | |
| zip([],_) -> []; | |
| zip([X|Xs],[Y|Ys]) -> [{X,Y}|zip(Xs,Ys)]. | |
| zip_test()-> | |
| ?assertEqual([ {1,2}, {3,4} ],zip([1,3,5,7], [2,4])), | |
| ok. | |
| % | |
| % b) Define a function zip_with/3 that “zips together” pairs of elements from two lists using the | |
| % function in the first argument, like this: | |
| % zip_with(fun(X,Y) -> X+Y end, [1,3,5,7], [2,4]) = [ 3, 7 ] | |
| % (thanks Peer Reynders) | |
| zip_with(_,[],_) -> []; | |
| zip_with(_,_,[]) -> []; | |
| zip_with(F,[X|Xs],[Y|Ys]) -> [F(X,Y)|zip_with(F,Xs,Ys)]. | |
| zip_wth_test()-> | |
| ?assertEqual([{1,2},{3,4}],zip([1,3,5,7], [2,4])), | |
| ok. | |
| % c) Re-define the function zip_with/3 using zip and lists:map. | |
| zip_with_map(F,X,Y)-> | |
| lists:map(fun({A,B}) -> F(A,B) end, zip(X,Y)). | |
| % d) Re-define zip/2 using zip_with/3. | |
| zip_with_zip_with(A,B) -> | |
| zip_with(fun (X,Y) -> {X,Y} end,A,B). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment