Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elixir fill a list with for loop

I wanted to fill a list with for-loop. I cheked this post here which has reason for why below code won't do it but then what will be my code to achieve it. I am newbie to elixir and from Java background

old_data = ['a','b','c','d']
new_data = []
for data <- old_data do
  new_data = List.insert_at(new_data, -1, data)
  IO.puts(new_data)
end
IO.puts(old_data)
IO.puts("new data is #{new_data}.")

There are few manipulations I have to do before adding elements to new_data so new_data = old_data is not something I am looking for

like image 963
veer7 Avatar asked Dec 18 '25 21:12

veer7


1 Answers

Elixir is (unlike Java) immutable. That said, one cannot modify any data inplace. Also, there is no for loop. There are no loops at all. Kernel.SpecialForms.for/1 is a comprehension.

That said, if you want to produce new list, you should do it explicitly. Unfortunately, it is impossible with Kernel.SpecialForms.for/1. We usually use a recursion for that.

defmodule Reverser do
  def go(input, output \\ [])                  # header
  def go([], output), do: Enum.reverse(output) # termination
  def go([h | t], output), do: go(t, [h | output])
end

Reverser.go([1, 2, 3])
#⇒ [1, 2, 3]

Also, here we use Enum.reverse/1 at termination because we prepended to the list during recursion, which is a way faster approach compared to append for linked lists.


Sidenote: IO.puts/1 output could be confusing, use IO.inspect/3 instead:

IO.inspect([1, 2, 3], label: "List")
#⇒ List: [1, 2, 3]

Sidenote #2: ['a','b','c','d'] is a list of lists. If you want a list of chars / strings, use double quotes. Yes, the meaning of single quotes and double quotes is drastically different.

is_list('a')
#⇒ true
'a' == [97]
#⇒ true
like image 100
Aleksei Matiushkin Avatar answered Dec 22 '25 11:12

Aleksei Matiushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!