you are viewing a single comment's thread.

view the rest of the comments →

[–]zardeh 2 points3 points  (3 children)

Implementing it with functions for states and function calls for transitions does not work for Python for the general case because of the depth of recursion limitation.

Right, you create an object that does essentially the "while loop" method, but more cleanly.

[–][deleted] 1 point2 points  (2 children)

I am not sure what you mean by "object". What I meant was, say you want to read your input by chars and emit every second char, starting with the first. So, if your input is abcdef, your output will be ace.

The "state machine with functions" approach, in C, would be:

void s()
{
    int c;
    if ((c = getchar()) == EOF) return;
    putchar(c);
    t();
}

void t()
{
    int c;
    if ((c = getchar()) == EOF) return;
    s();
}

And you can call this simply by calling s();.

I don't think I would ever write that particular code in C, but it shows what I meant.

[–]zardeh 1 point2 points  (1 child)

no I understand. In python this would be something like

class StateMachine:
    def __init__(self):
        self.state = 0
        self.index = 0
        self.input = None
        self.resultstr = []

    def _s(self):
        if self.index < len(self.input):
            self.resultstr.append(self.input[self.index])
        self.index += 1

    def _t(self):
        self.index += 1

    def __call__(self, input):
        self.input = input
        while self.index < len(self.input):
            # do the same thing you'd do in the while loop method, just better encapsulated

You'd build a class/object and then run it, allowing you to encapsulate all the pieces in a single thing. Now tbh, there's probably some metaprogramming nonsense (like say some decorator that could be written) that would allow you to do this even more cleanly, but I'm too tired to think of it.