Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
符号求异,中缀,处理了括号优化级
(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