This is a question that originated on the Elixir Slack from David Billskog and I have made only minor changes to the module.
Given this module:
defmodule Dummy do
def execute(x) do
with var_a <- get_a(x),
var_b <- get_b(x) do
IO.inspect(var_a, label: "a")
IO.inspect(var_b, label: "b")
IO.inspect({var_a, var_b})
if var_a != var_b do
IO.inspect(var_a, label: "a")
IO.inspect(var_b, label: "b")
IO.inspect({var_a, var_b})
end
end
end
defp get_a(x) do
IO.puts("get a")
if Enum.any?(x, & &1 == "A"), do: 3, else: 2
|> IO.inspect(label: "returning a")
end
defp get_b(x) do
IO.puts("get b")
if Enum.any?(x, & &1 == "B"), do: 2, else: 1
#|> IO.inspect(label: "returning b")
end
end
Dummy.execute(["A", "B"])
I get this unexpected output:
$ elixir sample.exs
get a
get b
a: 3
b: 2
{3, 2}
a: 3
b: 1
{3, 1}
Does anyone understand what is happening here? I don’t expect for the value of b
to change within the if statement, and I do expect the returning a
inspect to be printed. Tested on elixir 1.11.2-otp-23 and erlang 23.0.2.