-
Notifications
You must be signed in to change notification settings - Fork 122
/
recursion.erl
38 lines (30 loc) · 1015 Bytes
/
recursion.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
-module(recursion).
-export([recurse/1, fold/1, map/1, comprehension/1]).
%%
%% Example:
%% Different functions to capitalize a string
%%
%% BAD: makes unnecessary use of manual recursion
recurse(S) ->
lists:reverse(recurse(S, [])).
recurse([], Acc) ->
Acc;
recurse([H | T], Acc) ->
NewAcc = [string:to_upper(H) | Acc],
recurse(T, NewAcc).
%% GOOD: uses a fold instead to achieve the same result,
%% but this time more safely, and with fewer lines of code
fold(S) ->
Result = lists:foldl(fun fold_fun/2, [], S),
lists:reverse(Result).
fold_fun(C, Acc) ->
[string:to_upper(C) | Acc].
%% BETTER: uses a map instead of a fold to yield a simpler
%% implementation, since in this case a fold is overkill
map(S) ->
lists:map(fun string:to_upper/1, S).
%% BEST: in this case, a list comprehension yields the
%% simplest implementation (assuming we ignore the fact
%% that string:to_upper can also be used directly on strings)
comprehension(S) ->
[string:to_upper(C) || C <- S].