问题
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)
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
Any help?
回答1:
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
In 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
In 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
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
In 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
回答2:
Since for some reason you are not satisfied with a comprehension (why?) I would go with producing a helper function and using it in map.
defmodule Utils do
def do_stuff(x) do
x
|> ...
|> ...
|> ...
|> ...
|> Scraper.Abc.markup()
end
end
Enum.map(elements, &Utils.do_stuff/1)
来源:https://stackoverflow.com/questions/57189110/elixir-how-to-write-enum-map-in-block-instead-of-anonymous-function