简体   繁体   English

如何管道为循环elixir

[英]How to pipe in to for loop elixir

If I wanted to pipe into a case, I would do the following: 如果我想输入一个案例,我会做以下事情:

amount
|> calculate
|> case do
  1 -> "one"
  2 -> "two"
  _ -> "many"
end

Would it be possible to pipe into a for loop in a similar way, something like: 是否可以以类似的方式管道进入for循环,例如:

amounts
|> calculate
|> for do
  IO.inspect &1
end

or 要么

amounts
|> calculate
|> Kernel.for(&IO.inspect/1)

I am aware that I could use the Enum methods, but I am more curious about how the above could work. 我知道我可以使用Enum方法,但我更好奇上面的方法是如何工作的。

Unfortunately, this isn't possible. 不幸的是,这是不可能的。 The reason it works with case is that case is a macro whose first argument is a value and the second is the match clauses. 它与case工作的原因是case是一个宏,它的第一个参数是一个值,第二个是match子句。 for on the other hand has only one argument which includes all clauses and the do block: 另一方面, for只有一个参数,包括所有子句和do块:

iex(1)> quote do
...(1)>   for a <- 1..10, b <- 1..10, do: a + b
...(1)> end
{:for, [],
 [
   {:<-, [],
    [{:a, [], Elixir}, {:.., [context: Elixir, import: Kernel], [1, 10]}]},
   {:<-, [],
    [{:b, [], Elixir}, {:.., [context: Elixir, import: Kernel], [1, 10]}]},
   [
     do: {:+, [context: Elixir, import: Kernel],
      [{:a, [], Elixir}, {:b, [], Elixir}]}
   ]
 ]}

(As you can see, for takes onea argument which is the whole value a <- 1..10, b <- 1..10, do: a + b .) (正如你所看到的, for一个参数,它是整个值a <- 1..10, b <- 1..10, do: a + b 。)

The best you can do with for is to pipe into an anonymous function. 你可以做的最好for是管道进入一个匿名函数。 It isn't pretty but I have used this a couple of times when I wanted the functionality of for that isn't supported by Enum.each or Enum.map (multiple clauses, inline filters, into , etc). 这是不漂亮,但我已经使用这个一对夫妇的时候,我想的功能for所不支持Enum.eachEnum.map (多个条款,在线过滤器, into等)。

iex(2)> 1..5 |> (fn x -> for(i <- x, do: IO.puts(i)) end).()
1
2
3
4
5
[:ok, :ok, :ok, :ok, :ok]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM