Arithmetic Evaluator/Go: Difference between revisions

(Alternative solution using library functions)
imported>Katsumi
 
(2 intermediate revisions by one other user not shown)
Line 1:
__TOC__
=Operator precedence parser=
{{works with|gc|2010-04-27}}
 
This is an operator precedence parser. The number format used in calculation can be changed with the line "type Number int".
 
<langsyntaxhighlight lang="go">package main
 
import (
Line 230 ⟶ 228:
}
}
</syntaxhighlight>
</lang>
 
Example
Line 245 ⟶ 243:
</pre>
 
== External links ==
* [http[wp://en.wikipedia.org/wiki/Operator-precedence_parser#Pseudo-code Wikipedia:precedence parser|Operator-precedence parser]]
 
=Library=
Shown here is use of the package go/parser in the standard library. For the Go 1 release, there is a parser in the standard library, but not an evaluator. Evaluation is relatively easy though, once you have a parse tree.
Line 272 ⟶ 271:
"go", // a valid keyword, not valid in an expression.
"3@7", // error message is "illegal character."
"7D3", // the parser error message is a little strange here.
"", // EOF seems a reasonable error message.
}
Line 287 ⟶ 285:
 
func parseAndEval(exp string) (int, error) {
fstree, err := tokenparser.NewFileSetParseExpr(exp)
tree, err := parser.ParseExpr(fs, "", exp)
if err != nil {
return 0, err
Line 346 ⟶ 343:
go: 1:1: expected operand, found 'go'
3@7: 1:2: illegal character U+0040 '@'
7D3: 1:2: expected 'EOF', found 'IDENT' D3
: 1:1: expected operand, found 'EOF'
</pre>
Anonymous user