-
Notifications
You must be signed in to change notification settings - Fork 0
/
exercise46.ex
51 lines (43 loc) · 934 Bytes
/
exercise46.ex
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
39
40
41
42
43
44
45
46
47
48
49
50
51
defmodule Exercise46 do
def histogram(file) do
File.read(file)
|> words
|> frequency
|> sort
|> format
|> Enum.join("\n")
|> IO.puts
end
defp words({:ok, content}) do
content |> String.split
end
defp frequency(enum) do
Enum.reduce(enum, %{}, fn(word, acc) ->
Map.update(acc, word, 1, &inc/1)
end)
end
defp inc(value) do
value + 1
end
defp sort(enum) do
enum
|> Enum.sort_by(fn({word, value}) -> {-value, word} end)
end
defp format(enum) do
enum |> Enum.map(&(format_line(&1, max_word_length(enum))))
end
defp longest_word(enum) do
enum
|> Enum.map(&(elem(&1, 0)))
|> Enum.max_by(&String.length/1)
end
defp max_word_length(enum) do
enum
|> longest_word
|> String.length
|> inc
end
defp format_line({word, count}, max) do
"#{String.ljust(word <> ":", max)} #{String.duplicate("*", count)}"
end
end