ModularM
Modular2y ago
41 replies
bunny

Type State Pattern

Does anybody have a code-snippet that demonstrates a standard Type State Pattern in Mojo?

For example, a somewhat textbook-example of a traffic light -- please excuse any typos I make in my sloppy hand-jam example.

enum TrafficLight {
    Red,
    Green,
    Yellow,
}

impl TrafficLight {
    pub fn new() -> Self::Green { Self::Red }

    pub fn next(self: Self::Red) -> Self::Green { Self::Green }
    pub fn next(self: Self::Green) -> Self::Yellow { Self::Yellow }
    pub fn next(self: Self::Yellow) -> Self::Red { Self::Red }
}

fn main() {
    let mut light = TrafficLight::new(); // light is Red
    light = light.next();                // light is Green
    light = light.next();                // light is Yellow
    light = light.next();                // light is back to Red
}


Anyway, does anybody have a snippet of Mojo-style Type State Pattern? Google says "no," but I imagine somebody has a personal snippet they might share.
Was this page helpful?