Please explain this If statement behaviour

defmodule R do
def e(retry_num) do
    resp = {:error, "adsfs"}
    if retry_num==4 do
      resp
      else
        case resp do
            {:error, _body} ->
              e(retry_num + 1)
              any -> any
            end
      end
    end
end

in this module if statement prints resp variable to stdout but below one doesn’t

defmodule R do
  def e do
    resp = {:error, "dsd"}
    if resp == resp do
       resp
    else
       IO.puts "false!"
    end
    IO.puts("sd")
  end
end

Please format your code so its readable by inserting

```elixir

at the beginning and triple backticks at the end of the code blocks.

Secondly, what is the issue you are trying to solve? For what input are you expecting what output? Its not at all clear since you haven’t asked any question nor defined what you are trying to do. In your second module there isn’t even a variable called resp for example.

Lastly, you say “prints resp variable” but the first module has no IO statement so in fact nothing is printed. The only output is when iex inspects the final return from the function.

1 Like

sorry, edited the post.
my issue is the behaviour of IF statement, in some cases IF prints the variable to console and in some cases it does not

In which cases? Which function?

In the first function, any parameter to the function e/1 that is 4 or greater will have infinite recursion because you are constantly adding 1 and checking for the value 4.

2 Likes

The point @kip is making is that iex will inspect the return of a function.

In the first case the return is resp in the case where retry_num==4

In the second case the return is the result of IO.puts("sd") (because this comes after the if statement). The return of IO.puts is :ok.

3 Likes

i start by passing 0 to retry_num variable.
im trying to integrate a retry mechanism for web requests where i had this issue.

ok thanks for explaining, i got it now.
since resp was last statement in first module it returned, which is not the case in second module.

I would recommend looking at a package that does this work, for example retry. Retrying external API calls has a lot of edge cases, many potential error states and different strategies for retrying you might want. Not something you need to “roll your own”.

2 Likes

Yes, you are right - that’s what you are seeing.

1 Like

And, BTW, this is exactly why IO.inspect returns its argument–so you can use it at the end of a function to inspect return value, or insert it into the middle of a pipeline to see what’s going on.

3 Likes