Skip to content

Instantly share code, notes, and snippets.

@Joakineee
Last active May 16, 2020 09:37
Show Gist options
  • Save Joakineee/3fcb9ffb73e8fc790b1c2174b2476460 to your computer and use it in GitHub Desktop.
Save Joakineee/3fcb9ffb73e8fc790b1c2174b2476460 to your computer and use it in GitHub Desktop.
Tail recursive lists
-module(w2lists).
-export([prod/1,mymax/1,test/0]).
%Moddified according Elbrujohalcon:
%Removed the "list is emty" function clause as we will let it crash.
%prod([]) ->
% "list is empty";
prod([H|T]) ->
prod(T,H).
%Tail recursive prod.
prod([],Acc) ->
Acc;
prod([H|T],Acc) ->
prod(T,Acc * H).
%The product of an empty list is usually taken to be 1: why?
%because Acc starts by 1.
%This could be avoided by,for example, verifying that the list is not empty before calling prod/2.
%
%Moddified according Elbrujohalcon:
%Removed the "list is emty" function clause as we will let it crash.
%mymax([]) ->
% "list is empty";
mymax([H|T]) ->
mymax(T,H).
mymax([],Acc) ->
Acc;
mymax([H|T],Acc) ->
mymax(T,max(Acc,H)).
test() ->
3 = w2lists:prod([3]),
90 = w2lists:prod([1,3,5,6]),
54 = w2lists:mymax([1,23,4,54,23]),
ok.
@Joakineee
Copy link
Author

Excellent advice! thanks again!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment