0

Good day developers, i'm having issues figuring out how to make a function work.

Test case

  test "count one of each" do
    expected = %{"one" => 1, "of" => 1, "each" => 1}
    assert Words.count("one of each") == expected
  end

And this is what i came up with so far.

@spec count(String.t()) :: map
  def count(sentence) do
    sentence
    |> String.split
    |> Enum.map([sentence], &(%{sentence => 1 , value =>&1}))
  end
end

The code itself doesn't work, can some one explain how can i achieve the following functionality based on the test i provided?

Big thanks.

1
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. Commented Sep 30, 2018 at 13:34

2 Answers 2

4

From your code it looks like you haven't understood how pipes |> or the Enum functions work. It would probably benefit you to read the documentation in more detail.

This should do what you want:

"one of each"
|> String.split()
|> Enum.group_by(fn x -> x end)
|> Enum.map(fn {k, v} -> {k, length(v)} end) 
|> Enum.into(%{})

Explanation:

  1. Split the string into a list.
  2. Group the list into a map. The keys are the words, the value is a list containing each occurrence.
  3. Convert each list into a count of its length
  4. Return the result as a map
Sign up to request clarification or add additional context in comments.

Comments

2

Use Enum.reduce

  def count(sentence) do
    sentence
    |> String.split() 
    |> Enum.reduce(%{}, fn word, sentence_map -> 
        Map.update(sentence_map, word, 1, fn existing_count -> existing_count+1
        end) 
     end)
   end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.