Elixir:如何在块而不是匿名函数中编写Enum.map? [英] Elixir: How to write Enum.map in block instead of Anonymous function?

查看:126
本文介绍了Elixir:如何在块而不是匿名函数中编写Enum.map?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有生成关键字列表的函数,我想在调用scraper函数之前编写多行代码,如何使用map在块中编写此代码?

I have function which results me keyword list, I wanted to write mutiple lines of code before calling scraper function, how I can write this in block using map?

Enum.map(elements, fn(x) -> Scraper.Abc.markup(x) end)

我想写很多代码行,可以使用for循环,但不会给我带来任何结果

I wanted to write many code lines, I can use for loop but it will not result me anything

for elements <- x do
 x
 |> ...
 |> ...
 |> ...
 |> Scraper.Abc.markup
end

有帮助吗?

推荐答案


我想在调用scraper函数之前编写多行代码,

I wanted to write mutiple lines of code before calling scraper function,



defmodule A do
  def go do

    list = Enum.map([1, 2, 3], fn(x) -> 
      IO.puts "hello #{x}"
      str = String.upcase("goodbye #{x}")
      spawn(fn -> IO.puts str end)
      {:result, 2*x}
    end)

    IO.puts "list = #{inspect list}"

  end
end

在iex中:

iex(1)> A.go     
hello 1
GOODBYE 1
hello 2
GOODBYE 2
hello 3
GOODBYE 3
list = [result: 2, result: 4, result: 6]
:ok

或者,您可以这样做:

Or, you can do this:

defmodule A do
  def go do
    list = Enum.map([1, 2, 3], &my_func/1)
    IO.puts "list = #{inspect list}"
  end

  def my_func(x) do
    IO.puts "hello #{x}"
    str = String.upcase("goodbye #{x}")
    spawn(fn -> IO.puts str end)
    {:result, 2*x}
  end

end

在iex中:

iex(5)> A.go
hello 1
GOODBYE 1
hello 2
GOODBYE 2
hello 3
GOODBYE 3
list = [result: 2, result: 4, result: 6]
:ok




我可以使用for循环,但不会导致任何结果

I can use for loop but it will not result me anything



defmodule A do
  def go do

    list = for x <- [1, 2, 3] do
      x
      |> IO.inspect()
      |> Kernel.+(10)
      |> IO.inspect(label: "+10")
      |> Kernel.*(3)
      |> IO.inspect(label: "*3")
      |> do_stuff()
    end

    IO.puts "list = #{inspect list}"
  end

  def do_stuff(x), do: {:result, x * 100}
end

在iex中:

iex(3)> A.go     
1
+10: 11
*3: 33
2
+10: 12
*3: 36
3
+10: 13
*3: 39
list = [result: 3300, result: 3600, result: 3900]
:ok

这篇关于Elixir:如何在块而不是匿名函数中编写Enum.map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆