mazzie
Appending elements to a list
I have a list. I am trying to choose specific combinations from that list and making a list of list of those combinations.
My code runs something like this:
n = 6
list = [1,2,3,4,5,6]
n_list =
for i ← n..1 do
temp_list = List.delete_at(list,i-1)
[temp_list | n_list]
end
So basically i am removing one element at a time adding the resultant list to my list of list. temp_list is getting created correctly in each iteration. However that the end of the for n_list is still empty.
First Post!
wmnnd
Remember that in Elixir, all variables are immutable. So what you’’e doing there simply has no effect, neither on list nor on n_list. At the end of this code, list and n_list still point to the same values as they did before.
Last Post!
NobbZ
You can get that result with my function shown in Appending elements to a list - #6 by NobbZ
Your function does use imperative assignement and will produce warnings in Elixir 1.4 and newer (perhaps earlier, I’m not sure exactly when this has been deprecated) and will not work anymore in 2.0.
A version that works better were this:
def foo(list) when is_list(list), do: foo(list, Enum.count(list), [])
defp foo(list, 0, acc), do: acc
defp foo(list, n, acc) when n > 0, do: foo(list, n - 1, [List.delete_at(list, n - 1) | acc])
It has the same problems according runtime as my already shown version using for.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #hex
- #security









