Created
September 25, 2022 19:47
-
-
Save vKxni/3085311b15b8ab6e9056f7b3f3bb0b1b to your computer and use it in GitHub Desktop.
Count the number of words in the sentence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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