Other Clojure solutions.
(ns word-count
(:require [clojure.string :refer [split lower-case]]))
(defn word-count [s]
(let [words (split (lower-case s) #" ")
grouped-words (group-by identity words)]
(zipmap
(keys grouped-words)
(map count (vals grouped-words)))))
Other Elixir solutions.
defmodule WordCount do
@doc """
Count the number of words in the sentence.
Words are compared case-insensitively.
"""
@spec count(String.t()) :: map
def count(sentence) do
sentence
|> String.downcase()
|> String.split([" ", "_"])
|> Enum.map(&sanitize(&1))
|> Enum.filter(fn a -> String.length(a) > 0 end)
|> group_as_map
end
defp sanitize(str) do
str
|> String.trim()
|> String.replace(~r/[^-\w]/iu, "")
end
defp group_as_map(list_str) do
list_str
|> Enum.group_by(fn a -> a end)
|> Enum.map(fn {k, v} -> {k, length(v)} end)
|> Enum.into(%{})
end
end
Other Roc solutions.
module [countWords]
countWords : Str -> Dict Str U64
countWords = \sentence ->
sentence
|> Str.replaceEach "," " "
|> Str.split " "
|> List.map sanitizeWord
|> List.dropIf Str.isEmpty
|> List.walk (Dict.empty {}) \dict, word ->
Dict.update dict word \result ->
when result is
Ok existing -> Ok (existing + 1)
Err Missing -> Ok 1
sanitizeWord : Str -> Str
sanitizeWord = \word ->
word
|> Str.trim
|> Str.dropPrefix "'"
|> Str.dropSuffix "'"
|> Str.toUtf8
|> List.map \char -> if char >= 'A' && char <= 'Z' then char + 32 else char
|> List.keepIf \char -> (char >= 'a' && char <= 'z') || (char >= '0' && char <= '9') || char == '\''
|> Str.fromUtf8
|> Result.withDefault ""