Created
December 27, 2016 01:12
-
-
Save lucasrpb/f3ba5c68c433e0ecea84bd6b5b7d9f57 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
type Action struct { | |
Next interface{} | |
f func() | |
} | |
type Transition map[interface{}]Action | |
type Transitions map[interface{}]Transition | |
type FSM struct { | |
Start interface{} | |
Transitions Transitions | |
Final map[interface{}]bool | |
} | |
func (fsm *FSM) Parse(input string) { | |
cur := fsm.Start | |
size := len(input) | |
ts := fsm.Transitions | |
for i := 0; i < size; i++ { | |
c := rune(input[i]) | |
t := interface{}(ts[cur]).(Transition) | |
action, ok := interface{}(t[c]).(Action) | |
if !ok { | |
cur = nil | |
break | |
} | |
cur = action.Next | |
f := action.f | |
if f != nil { | |
f() | |
} | |
} | |
fmt.Println("valid:", fsm.Final[cur], cur) | |
} | |
func main() { | |
fsm := FSM{ | |
Start: 1, | |
Transitions: make(Transitions), | |
Final: map[interface{}]bool{ | |
3: true, | |
}, | |
} | |
ts := fsm.Transitions | |
ts[1] = Transition{ | |
'a': Action{ | |
2, | |
func() {}, | |
}, | |
} | |
ts[2] = Transition{ | |
'i': Action{ | |
3, | |
func() {}, | |
}, | |
} | |
ts[3] = Transition{} | |
fsm.Parse("ai") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment