Skip to content

Instantly share code, notes, and snippets.

@sudowork
Created March 26, 2013 11:17
Show Gist options
  • Select an option

  • Save sudowork/5244677 to your computer and use it in GitHub Desktop.

Select an option

Save sudowork/5244677 to your computer and use it in GitHub Desktop.
% map/2
Map = fun lists:map/2.
% increment using anon fn
Map(fun(X) -> X + 1 end, [1,2,3,4]).
% find powers of two
PowerOfTwo = fun(X) -> math:pow(2, X) end.
Map(PowerOfTwo, [1,2,3,4]).
% filter/2
Filter = fun lists:filter/2.
% keep evens
Filter(fun(X) -> X rem 2 == 0 end, lists:seq(1,10)).
% keep CS majors
Filter(fun({Major, _}) -> Major == cs end, [{cs, alice}, {ece, bob}, {cs, charlie}]).
% foldl/3
Foldl = fun lists:foldl/3.
% summation
Foldl(fun(X, Sum) -> Sum + X end, 0, [1,2,3,4,5]).
% reversing a list
Foldl(fun(X, R) -> [X|R] end, [], [1,2,3,4,5]).
% More higher-order functions
IsSmall = fun(X) -> X < 3 end.
lists:all(IsSmall, [0,1,2]). % => true
lists:all(IsSmall, [0,1,2,3]). % => false
lists:any(IsSmall, [0,1,2,3]). % => true
lists:any(IsSmall, [3,4]). % => false
lists:takewhile(IsSmall, [1,2,3,4]). % => [1,2]
lists:dropwhile(IsSmall, [1,2,3,4]). % => [3,4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment