Skip to content

Instantly share code, notes, and snippets.

@kylethebaker
Created June 28, 2017 01:24
Show Gist options
  • Save kylethebaker/ae0eec9c9435147d6049af2b4d0b8064 to your computer and use it in GitHub Desktop.
Save kylethebaker/ae0eec9c9435147d6049af2b4d0b8064 to your computer and use it in GitHub Desktop.
Week 2 - Functions Over Lists
-module(functions_over_lists).
-export([product/1]).
-export([maximum/1]).
-export([product_fold/1]).
product(X) -> product(X, 1).
product([], Product) -> Product;
product([X | Xs], Product) -> product(Xs, X * Product).
product_fold(Xs) ->
lists:foldl(fun(X, P) -> X * P end, 1, Xs).
% Return 'none' for empty lists
maximum([]) -> none;
% Initialize Max to the first list item
maximum([X | Xs]) -> maximum(Xs, X).
% When all items are exhausted, return held Max
maximum([], Max) -> Max;
% Replace Max when a list item is a number and larger than the current Max
maximum([X | Xs], Max) when is_number(X), X > Max -> maximum(Xs, X);
% Otherwise continue on to the next item
maximum([_ | Xs], Max) -> maximum(Xs, Max).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment