Remapping a variable in list comprehension

I am new to Elixir and functional programming coming from the background of OO.

I'm stuck trying to figure out how the reassignment variable works in Elixir in list comprehension. I expected the functions test1 () and test2 () to print 4, but test2 () does not reassign the variable and does not print 1.

defmodule SampleCode do
  def test1 do
    num = 1
    num = num + 1
    num = num + 2
    IO.puts num # Prints 4
  end

  def test2 do
    num = 1
    for i <- (1..2) do
      num = num + i
    end
    IO.puts num # Prints 1
  end
end
  • Why do these functions behave differently?
  • Is this a variable scope in Elixir or a basic principle of functional programming that I am missing?
+4
source share
2 answers

Elixir , ?

, .

Elixir , , case, cond receive, . :

num = 1

try do
  num = 2
after
  num = 3
end

num #=> 1

:

num = 1
(fn -> num = 2 end).()
num #=> 1

:

num = 1
case true do
  true -> num = 2
end
num #=> 2

num = 1
cond do
  true -> num = 2
end
num #=> 2

, , :

num = 1
case x do
  true  -> 2
  false -> num
end
#=> will return 1 or 2

, case. Elixir, , , Erlang - ( ) Elixir, if unless. , Elixir 2.0.

, , - Enum. Enum.sum/1, Enum.reduce/3 ( Enum , ).

+4

, , , , , * :

         BEFORE                         AFTER

defmodule SampleCode do     |  defmodule SampleCode do
  def test1 do              |    def test1 do
    num = 1                 |      num_1 = 1
    num = num + 1           |      num_2 = num_1 + 1
    num = num + 2           |      num_3 = num_2 + 2
    IO.puts num # Prints 4  |      IO.puts num_3
  end                       |    end
                            |
  def test2 do              |    def test2
    num = 1                 |      num_1 = 1
    for i <- (1..2) do      |      for i <- (1..2) do
      num = num + i         |        num_2 = num_1 + i
    end                     |      end
    IO.puts num # Prints 1  |      IO.puts num_1
  end                       |    end
end                         |  end

* Elixir - Erlang-Elixir Erlang.beam, Erlang. Erlang , Elixir .

FP Elixir, Erlang Erlang .

, , Erlang, Elixir:

1: test1() ->
2:     num@1 = 1,
3:     num@2 = num@1 + 1,
4:     num@3 = num@2 + 2,
5:    'Elixir.IO':puts(num@3).
6: test2() ->
7:     num@1 = 1,
8:     'Elixir.Enum':reduce(#{'__struct__' => 'Elixir.Range',
9:             first => 1, last => 2},
10:          [], fun (i@1, _@1) -> num@2 = num@1 + i@1 end),
11:    'Elixir.IO':puts(num@1).

11 - , , - num@1, Erlang 8-10 - , , , num@1, 1, , 7.

+4

Source: https://habr.com/ru/post/1606141/


All Articles