Last active
March 3, 2017 09:23
-
-
Save jason-carter/0572f9772743c9f1a1679725b6c02f30 to your computer and use it in GitHub Desktop.
FutureLearn Functional Programming In Erlang 2.6: Defining functions over lists
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
-module(listfuncs). | |
-export([productd/1, productt/1, productt/2]). | |
-export([listmaxd/1, listmaxt/1, listmaxt/2]). | |
% | |
% Combining list elements: the product of a list | |
% | |
% Direct Recursion | |
productd([]) -> 1; % The multiplying by 0 gives 0, so need to return 1 | |
productd([X|Xs]) -> X * productd(Xs). | |
% Tail Recursion | |
productt([]) -> 1; | |
productt(Xs) -> productt(Xs, 1). | |
productt([], Acc) -> Acc; | |
productt([X|Xs], Acc) -> productt(Xs, X*Acc). | |
% | |
% Combining list elements: the maximum of a list | |
% | |
% Direct recursion | |
listmaxd([X]) when X =/= [] -> X; | |
listmaxd([X|Xs]) -> (max(X, listmaxd(Xs))). | |
% Tail recursion | |
listmaxt(Xs) when Xs =/= [] -> listmaxt(Xs, 0). | |
listmaxt([X], Acc) -> max(Acc, X); | |
listmaxt([X|Xs], Acc) -> listmaxt(Xs, max(Acc, X)). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment