【发布时间】:2017-01-24 08:39:36
【问题描述】:
例如:
(* (* (* 1 2) 3) (* 4 5)) = (* 1 (* 2 (* 3 (* 4 5))))
我已经坐了几个小时想弄清楚如何编写这个程序,但我似乎无法让它工作。
生成的程序是(但是它没有按预期工作):
(define interpret-arithmetic-expression_Magritte_bizarre
(lambda (e)
(cond
[(is-literal? e)
(make-literal (literal-1 e))]
[(is-plus? e)
(if (is-plus? (plus-1 e))
(make-plus (interpret-arithmetic-expression_Magritte_bizarre (plus-1 (plus-1 e)))
(make-plus (interpret-arithmetic-expression_Magritte_bizarre (plus-2 (plus-1 e)))
(interpret-arithmetic-expression_Magritte_bizarre (plus-2 e))))
(make-plus (interpret-arithmetic-expression_Magritte_bizarre (plus-1 e))
(interpret-arithmetic-expression_Magritte_bizarre (plus-2 e))))]
[(is-times? e)
(if (is-times? (times-1 e))
(make-times (interpret-arithmetic-expression_Magritte_bizarre (times-1 (times-1 e)))
(make-times (interpret-arithmetic-expression_Magritte_bizarre (times-2 (times-1 e)))
(interpret-arithmetic-expression_Magritte_bizarre (times-2 e))))
(make-times (interpret-arithmetic-expression_Magritte_bizarre (times-1 e))
(interpret-arithmetic-expression_Magritte_bizarre (times-2 e))))]
[else
(errorf 'interpret-arithmetic-expression_Magritte
"unrecognized expression: ~s"
e)])))
【问题讨论】:
-
你有更详细的问题说明吗?或者可能是 + 运算符的示例?
-
为什么不
(* 1 2 3 4 5)? -
加号运算符也是同一个问题,即 (+ (+ 4 5) (+ 1 9)) = (+ 4 (+ 5 (+ 1 9)))
-
为什么不
(+ 4 5 1 9)?你觉得(+ (+ 3 (* 4 (+ 2 3))) 5)应该怎么处理? -
(+ 3 (+ (* 4 (+ 2 3)) 5)) - 基本上,我想要减号和加号的右关联属性。
标签: functional-programming scheme lisp