如何在另一个枚举中的枚举中声明管道列表?
How to declare a piped list in a Enum inside another Enum?
我正在尝试在另一个枚举中的一个枚举中使用管道列表。为了让自己更清楚一点,下面是我的代码:
def word_count(str) do
String.downcase(str)
|> String.split
|> Enum.map(fn x -> Enum.count(LIST HERE, x) end)
end
所以我想做的是在 Enum.count
中使用管道列表作为参数
枚举函数将可枚举作为第一个参数,因此您可以简单地将一个列表传递给它们。
如果想统计每个单词出现了多少次,可以使用Enum.frequencies/1
:
def word_count(str) do
str
|> String.downcase()
|> String.split()
|> Enum.frequencies()
end
示例:
iex> Example.word_count("foo bar baz")
%{"bar" => 1, "baz" => 1, "foo" => 1}
在这种情况下 Enum.frequencies/1
很有帮助,但您通常可以使用 Enum.reduce/3
来编写自己的逻辑。这是 Enum.frequencies/1
替换为 Enum.reduce/3
做同样的事情:
def word_count(str) do
str
|> String.downcase()
|> String.split()
|> Enum.reduce(%{}, fn word, acc ->
Map.update(acc, word, 1, fn count -> count + 1 end)
end)
end
为了回应评论,使用 Kernel.then/1
,免责声明可能有更好的方法来执行此操作,具体取决于所需内容(如上面的 reduce
,或使用理解):
1..10
|> then(fn one_to_ten ->
Enum.map(one_to_ten, fn x ->
Enum.map(one_to_ten, fn y ->
{x, y}
end)
end)
end)
如果你够摩登elixir (as you should be,) then/2
就是你的朋友
"Foo bar foo"
|> String.downcase()
|> String.split()
|> then(&Enum.map(&1, fn x -> Enum.count(&1, fn y -> y == x end) end))
#⇒ [2, 1, 2]
最易读的解决方案仍然是
words =
"Foo bar foo"
|> String.downcase()
|> String.split()
Enum.map(words, &Enum.count(words, fn x -> x == &1 end))
尽管可读性不佳,但不应尝试保留单个管道。
我正在尝试在另一个枚举中的一个枚举中使用管道列表。为了让自己更清楚一点,下面是我的代码:
def word_count(str) do
String.downcase(str)
|> String.split
|> Enum.map(fn x -> Enum.count(LIST HERE, x) end)
end
所以我想做的是在 Enum.count
中使用管道列表作为参数枚举函数将可枚举作为第一个参数,因此您可以简单地将一个列表传递给它们。
如果想统计每个单词出现了多少次,可以使用Enum.frequencies/1
:
def word_count(str) do
str
|> String.downcase()
|> String.split()
|> Enum.frequencies()
end
示例:
iex> Example.word_count("foo bar baz")
%{"bar" => 1, "baz" => 1, "foo" => 1}
在这种情况下 Enum.frequencies/1
很有帮助,但您通常可以使用 Enum.reduce/3
来编写自己的逻辑。这是 Enum.frequencies/1
替换为 Enum.reduce/3
做同样的事情:
def word_count(str) do
str
|> String.downcase()
|> String.split()
|> Enum.reduce(%{}, fn word, acc ->
Map.update(acc, word, 1, fn count -> count + 1 end)
end)
end
为了回应评论,使用 Kernel.then/1
,免责声明可能有更好的方法来执行此操作,具体取决于所需内容(如上面的 reduce
,或使用理解):
1..10
|> then(fn one_to_ten ->
Enum.map(one_to_ten, fn x ->
Enum.map(one_to_ten, fn y ->
{x, y}
end)
end)
end)
如果你够摩登elixir (as you should be,) then/2
就是你的朋友
"Foo bar foo"
|> String.downcase()
|> String.split()
|> then(&Enum.map(&1, fn x -> Enum.count(&1, fn y -> y == x end) end))
#⇒ [2, 1, 2]
最易读的解决方案仍然是
words =
"Foo bar foo"
|> String.downcase()
|> String.split()
Enum.map(words, &Enum.count(words, fn x -> x == &1 end))
尽管可读性不佳,但不应尝试保留单个管道。