在Elixir中引用管道值 [英] Referencing piped value in Elixir
本文介绍了在Elixir中引用管道值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想计算一个字符串中出现单词的次数。实现是有问题的,但是让我们用它来演示我的问题:
I want to count the number of word-occurrences in a string. The implementation is questionable, but lets use it to demonstrate my problem:
def count(sentence) do
words = String.split(sentence)
occurrences = Enum.map(words, fn w -> {w, Enum.count(words, &(&1 == w))} end)
Map.new(occurrences)
end
我希望获得与上述相同的结果,但使用管道代替中间结果变量:
I would like to achieve the same result as above, but using pipes instead of intermediate result variables:
def count(sentence) do
sentence
|> String.split
|> Enum.map(fn w -> {w, Enum.count(???)} end)
|> Map.new
end
是否可以引用枚举中的值。计数功能?还是我必须使用中间变量?
Is it possible to reference the piped in value in the Enum.count function? Or do i have to use an intermediate variable?
推荐答案
您可以在管道中放置一个匿名函数:
You can put an anonymous function in the pipeline:
def count(sentence) do
sentence
|> String.split
|> (fn words -> Enum.map(words, fn w -> {w, Enum.count(words, &(&1 == w))} end) end).()
|> Map.new
end
iex(1)> count("foo bar baz foo")
%{"bar" => 1, "baz" => 1, "foo" => 2}
这篇关于在Elixir中引用管道值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文