How can i access variables in if and else blocks and how to simulate a C++-return Statement in Elixir

Hi,
I’ve been studying elixir for four days. I want to change C++ code to Elixir.

As you can see in the C++ code: When a certain condition is reached, the return statement leaves the for-loop and the method. This eliminates the recursion and the result will be increased.

First, Elixir has no return-Statement, which makes it difficult to rewrite the code.
I also have problems with the scopes, which means that my result is always 0.

To better describe my problem, I would like to show you my code. I’ve been sitting for 16 hours now and I’m not making any progress. :frowning:

This is my C+±Code

int foo(someInput, int depth){
    ...
    int resultValue = 0;
    for(int i = 0; i < 5; ++i){
        do_some_stuff()
        if(condition1){
            if(condition2){
                return 1;
            }
            resultValue += foo(changed_someInputs, depth+1);
        }
    }
    return resultValue;
}

This is my Elixir Code

def foo(someInput, depth) do
      ...
      resultValue = 0
      continue = true    #too simulate a return-Statement. If condition2 is true -> change = false 
      for i <- 0..5 do
        if continue == true do
          #do_some_stuff
          if condition1 do
              if condition2 do
                resultValue = 1
                continue = false
              else
                resultValue =  resultValue + foo(change_someInput, depth+1) #I know that this is so wrong in functional Programming, but i dont know how i can solve this 
              end
            end
          end
        end
       resultValue  #is always zero. i guess because of the scopes
    end

Hi @lolicare95 welcome! As with all other functional languages, you’re going to have to think about programming pretty differently. The short version is that data is always immutable. You can’t change it, you just have to return new data.

Unfortunately, that’s about all the help I can provide, because the code you’ve presented is too abstract. If you’d like concrete help with specific code, you’ll need to provide an example function, and some expected input and output.

The second thing to note is that while you say you’ve been studying Elixir for 4 days, I’m curious about the resources you’ve been using. The official guides, as well as the main books like Programming Elixir provide very intuitive introductory material to help you get going on this process.

4 Likes

This code is highly not functional (using loops, and mutation), that is why it’s hard to translate…

But You can have a look at Enum.reduce_while

Not tested, but I would go for something like…

Enum.reduce_while(0..5, 0, fn x, acc -> 
  if condition1 && not condition2 do
    acc + foo(...)
  else
    {:halt, 1}
  end
end)
5 Likes

I think acc + foo(...) should be {:cont, acc + foo(...)}

5 Likes

Yes, You are right :slight_smile:

I did not mention that do_some_stuff() looks like a side effect. You need to think differently when doing FP, but it’s nice to see You can solve this with a one line solution…

Thank you so much, you’ve really helped me a lot. Thanks to your tips I could solve my problem. :heart_eyes:

I will read the documentation more thoroughly tomorrow. I noticed that I missed some important things. For example: {:halt, 1} or {:cont, acc + foo(...)}. Can you please tell me what that syntax is and how it is called?

@benwilson512, thank you for your answer :blush:. Yeah, you’re right, I have to think differently about functional programming. Which is really hard for me sometimes. I’ve never functionally programmed before. I am a student and have only learned C, C++ and Java (Object Oriented).

My approach to learning elixir was as follows:

  1. I googled what functional programming is
  2. afterwards I looked at a general Elixir tutorial to make it easier to get started (https://www.youtube.com/watch?v=pBNOavRoNL0&t)
  3. then I just started programming and checked the documentation every time I came across a problem or didn’t know something
1 Like

It is common to use tuples as response, like {:ok, …} | {:error, …}

In that case, it’s quite expressive, halt to stop, cont to continue.

Functions are differents… they are meant to be composable, and if possible, without side effect.

Returning a tuple can be easily used in pattern matching, and once You know about pattern matching, You wish You could use it everywhere.

1 Like

I know it can be hard but after 15 years doing object oriented programming and imperative for loops, I personally find the functional way of doing things is much more clean and easy to debug, because what you hold on to in each round of your loop is explicitly defined.

Enum.reduce_while is not exactly the easiest thing to start with. I recommend working to understand 1) Enum.map , then 2) Enum.reduce, then 3) Enum.flat_map.

Once you get the hang of doing those things you’ll be set.

3 Likes