Advertisement
Guest User

Untitled

a guest
Feb 7th, 2020
268
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scheme 1.84 KB | None | 0 0
  1. (define (make-mobile left right)
  2.     (cons left right))
  3.  
  4. (define (make-branch length structure)
  5.     (cons length structure))
  6.  
  7. (define (left-branch mobile)
  8.     (car mobile))
  9.  
  10. (define (right-branch mobile)
  11.     (cdr mobile))
  12.  
  13. (define (branch-length branch)
  14.     (car branch))
  15.  
  16. (define (branch-structure branch)
  17.     (cdr branch))
  18.  
  19.  
  20. (define (total-weight mobile)
  21.     (define (branch-weight branch)
  22.         (let ((structure (branch-structure branch)))
  23.             (cond ((pair? structure) (total-weight structure))
  24.                   (else structure))))
  25.     (+ (branch-weight (left-branch mobile)) (branch-weight (right-branch mobile))))
  26.  
  27. (define (balanced? mobile)
  28.     (define (branch-weight branch)
  29.         (let ((structure (branch-structure branch)))
  30.             (cond ((pair? structure) (total-weight structure))
  31.                   (else structure))))
  32.     (let ((left (left-branch mobile))
  33.           (right (right-branch mobile)))
  34.         (and (= (* (branch-weight left) (branch-length left))
  35.                 (* (branch-weight right) (branch-length right)))
  36.              (cond ((pair? (branch-structure left)) (balanced? (branch-structure left)))
  37.                    (else true))
  38.              (cond ((pair? (branch-structure right)) (balanced? (branch-structure right)))
  39.                    (else true)))))
  40.  
  41.  
  42. (define test-mobile (make-mobile
  43.                      (make-branch 4 3)
  44.                      (make-branch 3
  45.                                   (make-mobile (make-branch 2 2) (make-branch 2 2)))))
  46.  
  47. (define other-test-mobile (make-mobile
  48.                            (make-branch 4 4)
  49.                            (make-branch 4
  50.                                         (make-mobile (make-branch 1 2) (make-branch 2 2)))))
  51.  
  52.  
  53. (total-weight test-mobile)
  54. (total-weight other-test-mobile)
  55. (balanced? test-mobile)
  56. (balanced? other-test-mobile)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement