Created
February 28, 2017 02:27
-
-
Save javajosh/d17b546cc1c4eb52b89aa50d75cd1b9c to your computer and use it in GitHub Desktop.
Activity for Erlang course https://www.futurelearn.com/courses/functional-programming-erlang/1/steps/155134
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
%%%------------------------------------------------------------------- | |
%%% @author Josh Rehman | |
%%% @copyright (C) 2017, JavaJosh Enterprises | |
%%% @doc | |
%%% | |
%%% @end | |
%%% Created : 27. Feb 2017 5:28 PM | |
%%%------------------------------------------------------------------- | |
-module(l). | |
-author("Josh Rehman"). | |
%% API | |
-export([head/1,tail/1,second/1,sum/1, summ/1, prod/1,prodd/1, maxL/1, maxLL/1]). | |
% Trying out some examples from the video. | |
head([X|_Xs]) -> X. | |
tail([_X|Xs]) -> Xs. | |
%second(Xs) -> head(tail(Xs)). | |
% So the "cons" bar means "rest". | |
% The underscore suppresses unused parameter warning. | |
second([_X,Y|_Z]) -> Y. | |
% Calculate the sum of a list of numbers. Direct recursive. | |
sum([]) -> 0; | |
sum([X|Xs]) -> X + sum(Xs). | |
% Calculate the sum of a list of numbers. Indirect recursive. | |
summ(Xs) -> summ(Xs,0). | |
summ([],S) -> S; | |
summ([X|Xs], S) -> summ(Xs, X+S). | |
% Calculate the product of a list of numbers. Direct recursive. | |
prod([]) -> 1; | |
prod([X|Xs]) -> X * prod(Xs). | |
% Calculate the product of a list of numbers. Indirect recursive. | |
prodd(X) -> prodd(X, 1). | |
prodd([], Acc) -> Acc; | |
prodd([X|Xs], Acc) -> prodd(Xs, Acc * X). | |
% Note: the function name 'max' gave a scary warning. | |
%l.erl:43: Warning: ambiguous call of overridden auto-imported BIF max/2 use erlang:max/2 or "-compile({no_auto_import,[max/2]})." to resolve name clash | |
max2(A,B) when A>B -> A; | |
max2(_A,B) -> B. | |
% Calculate the max of a list. Direct recursive. | |
maxL([A]) -> A; | |
maxL([X|Xs]) -> max2(X, maxL(Xs)). | |
% Calculate the max of a list. Indirect recursive. | |
maxLL([X|Xs]) -> maxLL(Xs,X). | |
maxLL([A],Max) -> max2(A,Max); | |
maxLL([X|Xs], Max) when X > Max -> | |
maxLL(Xs, X); | |
maxLL([_X|Xs], Max) -> | |
maxLL(Xs, Max). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment