此Elixir表达式的正确语法是什么? [英] What is the correct syntax for this Elixir expression?
问题描述
已向我提供了此代码段,作者尚未对其进行测试,
I have been proferred this code snippet, which the author has not tested,
|> (fn l ->[?[, Enum.map(l, &([inspect(limit: :infinity), ?\n])), ?]] end).()
作为管道命令序列的一部分,该命令使用 DataMorph将数据从CSV文件转换为struct
库,并将结果作为常规的Elixir列表输出,以输入到Elixir源中-即添加括号,并用逗号分隔列表中的元素.
as part of a sequence of pipelined commands which converts data from a CSV file to a struct
using the DataMorph library, and outputs the result as a regular Elixir list for input into Elixir source - ie adding the surrounding brackets, and separating the elements of the list with commas.
以下是该序列的含义:
File.stream!('tmp.csv') \
|> DataMorph.structs_from_csv("open-register", :iso_country) \
|> (fn l ->[?[, Enum.map(l, &([inspect(limit: :infinity), ?\n])), ?]] end).()
|> (&File.write('output.txt',&1)).()
这是在iex
中运行时的错误消息:
This is the error message when it is run in iex
:
* (CompileError) iex:55: invalid args for &, expected an expression in the format of &Mod.fun/arity, &local/arity or a capture containing at least one argument as &1, got: [inspect(limit: :infinity), 10]
(elixir) expanding macro: Kernel.|>/2
iex:55: (file)
代码段哪里出问题了?
推荐答案
可以通过将&1
作为部分应用程序语法的第一个参数添加来修复语法错误:
The syntax error can be fixed by adding &1
as the first argument to the partial application syntax:
|> (fn l ->[?[, Enum.map(l, &([inspect(&1, limit: :infinity), ?\n])), ?]] end).()
此代码不包含逗号.为此,如果您想继续制作iolist,我建议您使用Enum.intersperse
:
This code doesn't include a separating comma. For that, if you want to stay with producing an iolist, I'd recommend using Enum.intersperse
:
iex(1)> [1, 2, [3], [4, 5]] |> (fn l ->[?[, Enum.map(l, &inspect(&1, limit: :infinity)) |> Enum.intersperse(",\n"), ?]] end).() |> IO.puts
[1,
2,
[3],
[4, 5]]
为了可读性,我还将其分成多行:
I'd also break this into multiple lines for readability:
[1, 2, [3], [4, 5]]
|> (fn list ->
elements = Enum.map(list, &inspect(&1, limit: :infinity)) |> Enum.intersperse(",\n")
[?[, elements, ?]]
end).()
|> IO.puts
这篇关于此Elixir表达式的正确语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!