temp_stats.erl in Erlang
A week of temperatures: a fold-picked extreme, bars, zip swings.
%% Summarize a week of temperature readings: extremes, mean, swings.
readings() ->
[{"Mon", -4.0}, {"Tue", -1.5}, {"Wed", 2.0}, {"Thu", 3.5},
{"Fri", 1.0}, {"Sat", -2.5}, {"Sun", -6.0}].
main(_) ->
Readings = readings(),
Temps = [T || {_, T} <- Readings],
{ColdDay, ColdT} = pick(fun erlang:'<'/2, Readings),
{WarmDay, WarmT} = pick(fun erlang:'>'/2, Readings),
io:format("Coldest: ~s at ~.1f C~n", [ColdDay, ColdT]),
io:format("Warmest: ~s at ~.1f C~n", [WarmDay, WarmT]),
io:format("Mean: ~.1f C~n", [lists:sum(Temps) / length(Temps)]),
%% Chart each day against the freezing line.
[begin
Len = max(1, trunc(T + 7)),
Side = if T > 0 -> "above"; true -> "below" end,
io:format("~-4s ~5.1f ~s ~s~n",
[Day, T, lists:duplicate(Len, $#), Side])
end || {Day, T} <- Readings],
%% Pair each temperature with its successor for the swings.
Swings = [abs(B - A)
|| {A, B} <- lists:zip(lists:droplast(Temps),
tl(Temps))],
io:format("Sharpest overnight swing: ~.1f C~n",
[lists:max(Swings)]).
pick(Cmp, [First | Rest]) ->
lists:foldl(fun({_, T} = E, {_, Best} = Acc) ->
case Cmp(T, Best) of true -> E; false -> Acc end
end, First, Rest).
How it works
pickfolds with a comparison fun passed in.- The chart duplicates $# against the freezing line.
zipover the list and its tail pairs the overnights.
Keywords and builtins used here
absbegincasedroplastduplicateendfoldlformatfuniflengthmainmaxofpickreadingssumtltrunczip
The run, in numbers
- Lines
- 35
- Characters to type
- 1132
- Tokens
- 411
- Three-star pace
- 55 tpm
At the three-star pace of 55 tokens a minute, this run takes about 448 seconds.
Step 3 of 3 in Encore, step 31 of 31 in Language basics.