简体   繁体   English

数学表达式的方案/球拍解释器

[英]Scheme/Racket interpreter for math expressions

I am trying to make a math-expression interpreter for a project, but I have difficulty in parsing unusual (unary) expressions like '(- -1), '(- (- -1)), '(* 10), '(/ 10) and other similar expressions.我正在尝试为一个项目制作一个数学表达式解释器,但我很难解析不寻常的(一元)表达式,如'(- -1), '(- (- -1)), '(* 10), '(/ 10)等类似的表达方式。

(define (math-eval expr)
  (define (helper op expr)
    (cond [(and (or (eqv? + op) (eqv? - op)) (null? expr)) 0]
          [(and (or (eqv? * op) (eqv? / op)) (null? expr)) 1]
          [(eqv? '+ (car expr)) (helper + (cdr expr))]
          [(eqv? '- (car expr)) (helper - (cdr expr))]
          [(eqv? '* (car expr)) (helper * (cdr expr))]
          [(eqv? '/ (car expr)) (helper / (cdr expr))]
          [(atom? (car expr))
           (op (car expr) (helper op (cdr expr)))]
          [else (+ (helper + (car expr)) (helper + (cdr expr)))]))
  (helper + expr))

This function accepts list and I think that the problem is in the atom?这个 function 接受列表,我认为问题出在原子上? option, but I am not sure how to fix it.选项,但我不知道如何解决它。 I would be very thankful if you could help me or give me directions how to solve my problem.如果您能帮助我或指导我如何解决我的问题,我将不胜感激。

Try to build math-eval recursively:尝试以递归方式构建math-eval

  • If expr is number, return that number.如果expr是数字,则返回该数字。
  • If expr is symbol of function, return that function.如果expr是 function 的符号,则返回 function。
  • If expr is list, evaluate each element of list and then use apply to call function (first element of list, car ) on numbers (rest of elements, cdr ).如果expr是列表,则评估列表的每个元素,然后使用apply在数字(其余元素, cdr )上调用 function(列表的第一个元素, car )。

Here is helper function, which returns function for given symbol:这是帮助程序 function,它为给定符号返回 function:

(define (fetch-function expr)
  (second
   (assoc expr (list (list '+ +)
                     (list '- -)
                     (list '* *)
                     (list '/ /)))))

Examples:例子:

> (fetch-function '+)
#<procedure:+>
> (fetch-function '-)
#<procedure:->

And here is recursive math-eval , working as described:这是递归math-eval ,按描述工作:

(define (math-eval expr)
  (cond ((number? expr) expr)
        ((symbol? expr) (fetch-function expr))
        (else (let ((op (car expr))
                    (args (cdr expr)))
                (apply (math-eval op)
                       (map math-eval args))))))

Examples:例子:

> (math-eval '(- -1))
1
> (math-eval '(- (- -1)))
-1
> (math-eval '(* 10))
10
> (math-eval '(/ 10))
1/10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM