How to return to the line of code and restore the call stack?

I asked the question before , but I don’t think I was clear enough about the answers that I was hoping for, so let me provide a more specific example:

class Program { private static bool State; static void Main(string[] args) { State = false; Console.WriteLine(And()); Console.ReadLine(); } static bool And() { return Or() && C(); } static bool Or() { return A() || AB(); } static bool C() { return State; } static bool A() { return true; } static bool AB() { State = true; return true; } } 

The flow of this program is as follows:

  • And () is called
  • And () calls Or ()
  • Or () calls A ()
  • A () returns true
  • The thread returns to Or (), which returns true (lazy evaluation)
  • The thread returns to calls to And (), And () C ()
  • C () returns false
  • The stream returns AND (), which returns false

Now, if Or () has not performed a lazy evaluation (changing || to | ), the program will return true. However, I do not want AB () to be executed if the result of the full analysis did not work (And () returns false).

So, what I would like to do is somewhere in the Or () function, save the current state on the stack (static variable), so that if And () returns false, I can pull an element from the stack and try an alternative.

How would this be done in C #?

0
source share
2 answers

It seems to me that this is pretty trivial - just reorder the calls:

 static void Main(string[] args) { State = false; Console.WriteLine(Or()); Console.ReadLine(); } static bool Or() { return A() && C() || AB() && C(); } 

Or am I missing something? Maybe C() has side effects so that it cannot be called twice?

EDIT: Now I understand what you are trying to do. Do yourself a favor. Listen to the suggestions you received, get a copy of the GPPG or (possibly much easier) ANTLR , with ANTLRWorks . This is much easier and less error prone than trying to steer the parser manually, and you still get C # at the end.

+1
source

The problem has nothing to do with || operator. The problem is that you forgot to return to the failed parse. If Parse returns false, you need to restore i and any other state variables to their original value so that the next parser can try. C # is not the target language. If you want to return, you will have to do it yourself. (Or switch to a countdown language like Prolog.)

+2
source

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


All Articles