summaryrefslogtreecommitdiff
path: root/src/code/2/wc_2.exs
blob: f7e97e9dc55a9e56f8247669e6251ddf45bf3427 (plain)
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
defmodule WordCount do

  defp stream_file(filename) do
    File.stream!(filename)
  end

  defp tokenize_words(line) do
    line |> Stream.flat_map(&String.split/1)
  end

  defp reduce_words(words) when is_list(words) do
    Enum.reduce(words, %{}, &update_count/2)
  end

  defp update_count(word, acc) do
    Map.update(acc, word, 1, &(&1 + 1))
  end

  def count_words(filename) do
    stream_file(filename)
    |> tokenize_words
    |> Stream.map(&String.downcase/1)
    |> Enum.to_list
    |> reduce_words
  end

end

WordCount.count_words("pg51353.txt") |> IO.inspect(limit: 20)