Created
March 6, 2014 13:01
-
-
Save muhqu/9389069 to your computer and use it in GitHub Desktop.
This file contains 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
g := NewGrammar("Math", func(g GrammarInit) { | |
Digit := Accept("0123456789") | |
tNumber := NewLexItemType("Num") | |
Number := OneOrMore(Digit).CaptureAsWithConversion(tNumber, func(str string) interface{} { | |
val, _ := strconv.ParseInt(str, 10, 64) | |
return val | |
}) | |
tPlus := NewLexItemType("Plus") | |
Plus := Accept("+").CaptureAs(tPlus) | |
tEquality := NewLexItemType("Equal") | |
Equality := Accept("=").CaptureAs(tEquality) | |
g.Add(Number) | |
g.Add(Plus) | |
g.Add(Equality) | |
}) | |
items := g.ParseString(`2 + 2 = 4`) | |
for _, item := range items { | |
fmt.Printf("%-6s %-8T %#v\n", item.Type(), item.Value(), item.Value()) | |
} | |
// Output: | |
// Num int64 2 | |
// Plus string "+" | |
// Num int64 2 | |
// Equal string "=" | |
// Num int64 4 | |
// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment