Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions lib/elixir/lib/enum.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1147,6 +1147,27 @@ defmodule Enum do
end)
end

@doc """
creates a new map with keys as unique elements from enumerable,
and set values as the count of every element

The order of elements within each list is preserved from the `enumerable`.

## Examples

iex> Enum.tally(~w{ant buffalo ant ant buffalo dingo})
%{"ant" => 3, "buffalo" => 2, "dingo" => 1}

iex> Enum.tally(~w{aa aA bb cc}, fn x -> String.downcase(x) end)
%{"aa" => 2, "bb" => 1, "cc" => 1}
"""
@spec tally(t, (element -> any)) :: map
def tally(enumerable, func \\ fn x -> x end) do
group_by(enumerable, func)
|> map(fn {key, val} -> {key, count(val)} end)
|> Map.new()
end

@doc """
Intersperses `element` between each element of the enumeration.

Expand Down
10 changes: 10 additions & 0 deletions lib/elixir/test/elixir/enum_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,16 @@ defmodule EnumTest do
assert Enum.group_by([1, 2, 3], &rem(&1, 2)) == %{0 => [2], 1 => [1, 3]}
end

test "tally/2" do
assert Enum.tally(~w{a a a b c c}) == %{"a" => 3, "b" => 1, "c" => 2}

assert Enum.tally(~w{aa aA bb cc}, fn x -> String.downcase(x) end) == %{
"aa" => 2,
"bb" => 1,
"cc" => 1
}
end

test "intersperse/2" do
assert Enum.intersperse([], true) == []
assert Enum.intersperse([1], true) == [1]
Expand Down