Javascript-从字符串解析多项式 [英] Javascript - Parse Polynomials From String

查看:113
本文介绍了Javascript-从字符串解析多项式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在Objective-c 此处询问过此问题,但需要答案很快,并且能够使用Objective-C或javascript进行解析,因此我将在此处询问js.

I Just Asked this question for objective-c here, but need the answer quick and am able to do the parsing in either objective-c or javascript, so I will ask for js here.

在我的应用程序中,用户将以字符串形式输入数学表达式,例如n*3/7+9-5,我需要能够从该字符串中获得多项式,例如4, 3/7, 0, 0, 0, 0,有没有办法做到这一点或将在javascript中执行此操作的库?我正在使用节点,因此最好是与节点兼容的东西.

In my app the user will be inputting a mathematical expression as a string, such as n*3/7+9-5, and I need to be able to get the polynomials from that string, like 4, 3/7, 0, 0, 0, 0, is there a way to do this or a library that will do this in javascript? I am using node, so preferably something that is node compatible.

我已经在Google上进行了一些研究,但似乎一无所获,而且我也不知道该如何亲自编写.

I have done some research on google, but there appears to be nothing, and I have no idea how to go about writing it myself.

推荐答案

您也可以在线尝试 http://zaach.github.io/jison/try/

计算器语法是这样的,我也在学习,这有点难以理解

calculator grammer is like this I am also learning this it is little bit difficult to understand

来自 http://zaach.github.io/jison/try/:

From http://zaach.github.io/jison/try/ :

/* 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 '!'
        {{
          $$ = (function fact (n) { return n==0 ? 1 : fact(n-1) * n })($1);
        }}
    | e '%'
        {$$ = $1/100;}
    | '-' e %prec UMINUS
        {$$ = -$2;}
    | '(' e ')'
        {$$ = $2;}
    | NUMBER
        {$$ = Number(yytext);}
    | E
        {$$ = Math.E;}
    | PI
        {$$ = Math.PI;}
    ;

这篇关于Javascript-从字符串解析多项式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆