Last active
March 3, 2017 02:02
-
-
Save paucus/12d7e59041abe5c4c05962075577294a to your computer and use it in GitHub Desktop.
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
% Marcelo Ruiz Camauër | |
% assignment 2.6 | |
-module(a26). | |
-export([listprod/1,listprod2/1,listmax/1,listmax2/1]). | |
% define an Erlang function to give the product of a list of numbers. | |
% The product of an empty list is usually taken to be 1 | |
% recursive listprod(): | |
listprod([]) -> 1; | |
listprod([H|T]) -> H * listprod(T). | |
% Define an Erlang function to give the maximum of a list of numbers. | |
% tail recursive listmax(): | |
listmax(L) when L /= [] -> listmax(tl(L),hd(L)). % only valid for non-empty lists! | |
listmax([],_Item) -> _Item; % when no more items in list we have the max item. | |
listmax([H|T],Maxitem) -> listmax(T,max(H,Maxitem)). % keep the max item, recurse on the rest of the list. | |
% In each case you could give either a direct recursion or a tail recursive definition. | |
% Give the other kind of definition for product and maximum. | |
% tail recursive listprod(): | |
listprod2([]) -> 1; | |
listprod2([H|T]) -> listprod2(T,H). | |
listprod2([],Acc) -> Acc; | |
listprod2([H|T],Acc) -> listprod2(T,H * Acc). | |
% recursive listmax(): | |
listmax2([L]) when L/=[] -> L; | |
listmax2([H|T]) -> (max(H,listmax2(T))). % keep the max item, recurse on the rest of the list. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment