MisterLimao Ml
MisterLimao Ml

Reputation: 63

Add new element to list using for

I do not know how best to solve this in elixir but given a number to make print its sequence like this [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:

n = 10
list = []
for i <- 0..n - 1, do: list = list ++ [i]
IO.inspect list

This code above returns me this:

warning: variable "list" is unused
    solution.ex:8

** (UndefinedFunctionError) function Solution.main/0 is undefined or private
    Solution.main()
    (elixir) lib/code.ex:677: Code.require_file/2

Upvotes: 1

Views: 79

Answers (4)

Bitwise
Bitwise

Reputation: 8461

I'll add another one to the mix.

The classic Enum.map/2

n = 10
list = Enum.map(0..n-1, &(&1))
IO.inspect list

Not quite as concise as Enum.to_list/1 but a little more versatile.

Upvotes: 1

Justin Wood
Justin Wood

Reputation: 10061

Elixir's variables are scoped to the "block" that they are in. Lets see what that looks like with your code.

n = 10
outer_list = []
for i <- 0..n - 1, do: inner_list = outer_list ++ [i]
IO.inspect outer_list

So the value of inner_list will always be [] ++ [i] because outer_list is not being changed. When you named both inner_list and outer_list to just list, you are shadowing the variable. Meaning it has the same name, but different value based on the scope. You are also getting a warning stating that inner_list is not actually used anywhere.

What you probably want to do is

n = 10
list = for i <- 0..n - 1, do: i
IO.inspect list

Though, you may be better served using Enum.to_list/1.

n = 10
list = Enum.to_list(0..n-1)
IO.inspect list

Upvotes: 6

Nathan Ripert
Nathan Ripert

Reputation: 890

While @neisc gave a good answer, I would rather do:

list = list ++ (for i <- 0..(n - 1) do i end)

Which add something to the original list while also keeping the data that it might already contain.

Upvotes: 1

neiesc
neiesc

Reputation: 653

Try using list comprehensions like:

list = for i <- 0..(n - 1) do i end
IO.inspect list

Upvotes: 5

Related Questions