如何在Elixir中使用Enum
函數將兩個數組合並在一起?Elixir - 合併2列表列表(如列)
E.g.
points = [[1.0, 2.0],
[5.0, 3.0],
[2.0, 4.0],
[3.0, 1.0],
[2.0, 2.0],
[4.0, 3.0],
[1.0, 2.0],
[2.0, 5.0],
[14.0, 13.0],
[11.0, 12.0],
[12.0, 15.0],
[32.0, 25.0]]
results = [1.0,
3.0,
2.0,
1.0,
3.0,
2.0,
1.0,
3.0,
2.0,
1.0,
3.0,
2.0]
的組合陣列(列加),應該是這樣的:
combined = [[1.0, 2.0, 1.0],
[5.0, 3.0, 3.0],
[2.0, 4.0, 2.0],
[3.0, 1.0, 1.0],
[2.0, 2.0, 3.0],
[4.0, 3.0, 2.0],
[1.0, 2.0, 1.0],
[2.0, 5.0, 3.0],
[14.0, 13.0, 2.0],
[11.0, 12.0, 1.0],
[12.0, 15.0, 3.0],
[32.0, 25.0, 2.0]]
好像這樣的事情應該工作:
points
|> Stream.with_index
|> Enum.map(fn({x,i}) -> Enum.into(x, Enum.fetch!(results, i)) end)
雖然,這將產生一個錯誤:
** (Protocol.UndefinedError) protocol Collectable not implemented for 1.0. This protocol is implemented for: BitString, Ecto.Adapters.SQL.Stream, File.Stream, HashDict, HashSet, IO.Stream, List, Map, MapSet, Plug.Conn, Postgrex.Stream
(elixir) lib/collectable.ex:1: Collectable.impl_for!/1
(elixir) lib/collectable.ex:77: Collectable.into/1
(elixir) lib/enum.ex:1158: Enum.into_protocol/2
(elixir) lib/enum.ex:1259: anonymous fn/3 in Enum.map/2
(elixir) lib/enum.ex:1824: anonymous fn/3 in Enum.map/2
(elixir) lib/stream.ex:1413: anonymous fn/3 in Enumerable.Stream.reduce/3
(elixir) lib/stream.ex:978: anonymous fn/3 in Stream.with_index/2
(elixir) lib/enum.ex:3161: Enumerable.List.reduce/3
(elixir) lib/stream.ex:1433: Enumerable.Stream.do_each/4
(elixir) lib/enum.ex:1823: Enum.map/2
太棒了,我真的很喜歡答案 –