简体   繁体   中英

Elixir: clone a list idiomatically

I can always do something like this:

new_list = Enum.map(old_list, fn x -> x end)

There is a dozen more equally, or marginally less ugly, ways of doing so, of course. Somehow, I can't find an idiomatic way of copying a list. There certainly must be a way.

Elixir is an immutable language, so the idiomatic way is this:

clone = original

There is no need to "clone". The data assigned to existing variables cannot be edited, so assigning one variable to another conceptually results in a copy of the data. You cannot edit existing data - if you reassign to an existing variable, you are conceptually pointing that variable at a new data-structure.

original = [1, 2, 3] |> IO.inspect(label: "original")
clone = original |> IO.inspect(label: "clone")
prepended = [0 | original] |> IO.inspect(label: "prepended")
original |> IO.inspect(label: "original again")
original = [5, 6, 7] |> IO.inspect(label: "original rebound")
clone |> IO.inspect(label: "clone again")

Output:

original: [1, 2, 3]
clone: [1, 2, 3]
prepended: [0, 1, 2, 3]
original again: [1, 2, 3]
original rebound: [5, 6, 7]
clone again: [1, 2, 3]

Since data structures in Elixir are immutable, I can't think of a reason you'd ever need to "clone" a list. It would do nothing. That being said, if you're looking for a way to do that exact nothing, you could reach for Enum.to_list/1 .

iex> Enum.to_list([1, 2, 3])
[1, 2, 3]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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