Skip to content

Instantly share code, notes, and snippets.

@muhqu
Created March 6, 2014 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muhqu/9389069 to your computer and use it in GitHub Desktop.
Save muhqu/9389069 to your computer and use it in GitHub Desktop.
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