Skip to content

Instantly share code, notes, and snippets.

@vKxni
Created September 25, 2022 19:47
Show Gist options
  • Save vKxni/3085311b15b8ab6e9056f7b3f3bb0b1b to your computer and use it in GitHub Desktop.
Save vKxni/3085311b15b8ab6e9056f7b3f3bb0b1b to your computer and use it in GitHub Desktop.
Count the number of words in the sentence
defmodule Utils.WordCount do
@doc """
Count the number of words in the sentence.
Words are compared case-insensitively.
"hello there"
hello: 5
friends: 7
"""
@spec count(String.t()) :: map
def count(sentence) do
sentence
|> String.downcase()
|> String.split(~R/[^\p{L}\p{N}-]+/u)
|> Enum.reduce(%{}, fn word, map -> Map.update(map, word, 1, &(&1 + 1)) end)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment