Skip to content

Instantly share code, notes, and snippets.

@korzio
Last active March 17, 2021 20:38
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 korzio/dcacf6a73277d98253c280358d58fef2 to your computer and use it in GitHub Desktop.
Save korzio/dcacf6a73277d98253c280358d58fef2 to your computer and use it in GitHub Desktop.
tree := p.lexer.Tokens().
Scan(func(_ context.Context, acc interface{}, elem interface{}) (interface{}, error) {
it, isIterator := acc.(iterator)
next := elem.(token.Token)
if !isIterator || it.left == nil {
// null denotation
return nud(acc, next), nil
}
if it.operator != nil {
var prevIt *iterator
if len(it.stack) > 0 {
prevIt = &it.stack[len(it.stack)-1]
}
// binding power comparison
for len(it.stack) > 0 && prevIt != nil && bp(it.operator) < bp(prevIt.operator) {
prevIt = &it.stack[len(it.stack)-1]
// left denotation
it.left = led(*prevIt.left, *prevIt.operator, *it.left)
// in golang slices are immutable
it.stack = it.stack[:len(it.stack)-1]
}
var newIt iterator
newIt.stack = append(it.stack, it)
// next iteration
return nud(newIt, next), nil
}
it.operator = &next
return it, nil
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment