[Question]: Getting enum values

Which algebraic expression is simpler?

1. a*b*c + a*b*d
2. a*b*(c + d)

If you're evaluating an algebraic expression it can help to put it in minimal form. Structs and enums are called algebraic data types because you can do the same thing. Factor out the common stuff to another struct.

struct Type {
    value: Value,
    start: Position,
    end: Position,
}

enum Value {
    Int(i32),
    Float(f32),
}

impl Type {
    pub fn plus_op(&self, other: Type) -> RTResult {
        // use a tuple to match both at once so you don't need to nest `match`es
        match (self.value, other.value) {
            (Value::Int(this), Value::Int(that)) => { ... }
            (Value::Float(this), Value::Float(that)) => { ... }
            (v, w) => { /* error handling code */ }
        }
    }
}
5 Likes