我这里有一个 JISON 计算器示例的稍微修改过的版本:
/* description: Parses end executes mathematical expressions. */
/* lexical grammar */
%lex
%%
\s+ /* skip whitespace */
[0-9]+("."[0-9]+)?\b return 'NUMBER'
"*" return '*'
"/" return '/'
"-" return '-'
"+" return '+'
"^" return '^'
"!" return '!'
"%" return '%'
"(" return '('
")" return ')'
"PI" return 'PI'
"E" return 'E'
<<EOF>> return 'EOF'
. return 'INVALID'
/lex
/* operator associations and precedence */
%left '+' '-'
%left '*' '/'
%left '^'
%right '!'
%right '%'
%left UMINUS
%start expressions
%% /* language grammar */
expressions
: e EOF
{ typeof console !== 'undefined' ? console.log($1) : print($1);
return $1; }
;
e
: e '+' e
{$$ = $1+$3;}
| e '-' e
{$$ = $1-$3;}
| e '*' e
{$$ = $1*$3;}
| e '/' e
{$$ = $1/$3;}
| e '^' e
{$$ = Math.pow($1, $3);}
| e '!'
{{
$$ = fact($1);
}}
| e '%'
{$$ = $1/100;}
| '-' e %prec UMINUS
{$$ = -$2;}
| '(' e ')'
{$$ = $2;}
| NUMBER
{$$ = Number(yytext);}
| E
{$$ = Math.E;}
| PI
{$$ = Math.PI;}
;
%%
/*why doesn't this work at runtime?
I see other examples defining declarations this way but I must be doing something wrong
I couldn't find a syntactically valid way of putting this declaration anywhere but here,
which is probably the issue*/
function fact(n) {
var tot=1;
for(var i=2;i<=n;++i) {
tot*=i;
}
return tot;
}
!
请注意操作员定义的细微差别。我试图从外部定义fact
函数而不是内联。
截至目前,它在运行时告诉我fact is not defined
。我怎样才能解决这个问题?另外,为什么计算器示例在阶乘定义周围使用两个大括号{{ /*like so*/ }}
?