jweinst1
7/12/2016 - 11:48 PM

enum automata for swift

enum automata for swift

//playground to make integer automatan

//instruction for math machine
enum Instruction {
    case op(String)
    case int(Int)
}

enum Math {
    static let opers = [
        "+":{(a:Int, b:Int) in a + b},
        "-":{(a:Int, b:Int) in a - b},
        "*":{(a:Int, b:Int) in a * b},
        "/":{(a:Int, b:Int) in a / b},
        "%":{(a:Int, b:Int) in a % b}
    ]
    
    static let transitions = [
        "+":{(amount:Int) in Math.state(amount:amount, oper:"+")},
        "-":{(amount:Int) in Math.state(amount:amount, oper:"-")},
        "*":{(amount:Int) in Math.state(amount:amount, oper:"*")},
        "/":{(amount:Int) in Math.state(amount:amount, oper:"/")},
        "%":{(amount:Int) in Math.state(amount:amount, oper:"%")}
    ]
    case state(amount:Int, oper:String)
    
    init(amount:Int, op:String) {
        self = Math.transitions[op]!(amount)
    }
    
    
    mutating func input(code:Instruction) {
        switch code {
        case .op(let oper):
            switch self {
            case state(let amount, _):
                self = Math.state(amount: amount, oper: oper)
            }
        case .int(let int):
            switch self {
            case state(let amount,let oper):
                self = Math.state(amount: Math.opers[oper]!(amount, int), oper: oper)
            }
        }
    }
}