home » 2015 » 02 » How Generic Dispatch Works in Factor

How Generic Dispatch Works in Factor

Posted:
2015-02-06
Tags:
generics factor

Generic methods is Factor's version of object oriented programming. In other languages, you have a class, struct or record and attached to that is a set of functions or methods.

class Parser:
    def __init__(self):
        self.state = ...
    def consume_text(self, str):
        ...

p = Parser()
p.consume_text("some text to parse")

Now, if you have used Python for a while you know that its method call syntax is basically just syntactic sugar over a function call with the class instance as the first argument. Kind of like this:

p = Parser()
consume_text(p, "some text to parse")

Complications arise when you have multiple classes that all define a consume_text method. How will Python know which function to dispatch to? Behind the scenes, it has some complicated machinery for determining which function to invoke. Factor has the exact same features, but packaged a little differently.

Continuing with the parser example, here is how you would define it in Factor:

TUPLE: parser state ;

GENERIC: consume-text ( x -- )

M: parser consume-text ( x -- )
    ... ;

{ } parser boa "hello there" swap consume-text

Python dispatches on the first argument given to the function, Factor dispatches on element on the top of the stacks class. If that element has the type parser, then the word M: parser consume-text is called.