Created
July 30, 2019 18:34
-
-
Save yszou/d0cbe78246c487365045d2861a6e07fa to your computer and use it in GitHub Desktop.
符号求异,中缀,处理了括号优化级
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(define (=number? a v) (and (number? a) (= a v))) | |
(define (variable? e) (symbol? e)) | |
(define (sum? e) | |
(and (pair? e) (eq? (cadr e) '+))) | |
(define (sum-a e) (car e)) | |
(define (sum-b e) | |
(if (= (length e) 3) (caddr e) (cdr (cdr e)))) | |
(define (make-sum a b) | |
(cond ((=number? a 0) b) | |
((=number? b 0) a) | |
((and (number? a) (number? b)) (+ a b)) | |
(else (list a '+ b)))) | |
(define (product? e) | |
(and (pair? e) (eq? (cadr e) '*))) | |
(define (product-a e) (car e)) | |
(define (product-b e) | |
(if (= (length e) 3) (caddr e) (cdr (cdr e)))) | |
(define (make-product a b) | |
(cond ((=number? a 0) 0) | |
((=number? b 0) 0) | |
((=number? a 1) b) | |
((=number? b 1) a) | |
(else (list a '* b)))) | |
;只给乘法添加括号 | |
(define (add-parentheses e) | |
(cond ((number? e) e) | |
((symbol? e) e) | |
((sum? e) | |
(if (= (length e) 3) e | |
(list (left e) '+ (add-parentheses (big-tail e))))) | |
((product? e) | |
(if (= (length e) 3) (list (left e) '* (right e)) | |
(add-parentheses (append (list (list (left e) '* (right e))) (tail e))))) | |
(else '()))) | |
(define (left e) (car e)) | |
(define (right e) (caddr e)) | |
(define (tail e) (cdr (cdr (cdr e)))) | |
(define (big-tail e) (cdr (cdr e))) | |
(define (df e v) | |
(define (df-do e v) | |
(cond ((variable? e) (if (eq? e v) 1 0)) | |
((number? e) 0) | |
((sum? e) (make-sum (df (sum-a e) v) (df (sum-b e) v))) | |
((product? e) | |
(make-sum (make-product (product-a e) (df (product-b e) v)) | |
(make-product (product-b e) (df (product-a e) v)))) | |
(else | |
'()))) | |
(df-do (add-parentheses e) v)) | |
;(display (df '(x + (3 * (x + (y + 2)))) 'x)) | |
;(display (df '(x * y * z) 'x)) | |
(display (df '(3 * x + x * y) 'x)) | |
;(display (df '(x + 3 * (x + y + 2)) 'x)) | |
;(display (add-parentheses '(x + 3 * (x + y + 2)))) | |
;(display (add-parentheses '(3 * x + x * y))) | |
;(display (add-parentheses '(3 + 2 + x * y))) | |
;(display (add-parentheses '(x + y + z))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment