eval.scm 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. (define (square x) (* x x))
  2. (define (sum-of-squares x y)
  3. (+ (square x) (square y)))
  4. (define (f a)
  5. (sum-of-squares (+ a 1) (* a 2)))
  6. ;; eager
  7. ;; (f 5)
  8. ;; (sum-of-squares (+ 5 1) (* 5 2))
  9. ;; (+ (square (+ 5 1)) (square (* 5 2)))
  10. ;; (+ (* (+ 5 1) (+ 5 1)) (* (* 5 2) (* 5 2)))
  11. (define (f2 a)
  12. (let ((v #f)
  13. (r #f)
  14. (r2 #f)
  15. (x #f))
  16. (define (square!) (set! r (* x x)))
  17. (set! x (+ a 1))
  18. (square!)
  19. (set! r2 r)
  20. (set! x (* a 2))
  21. (square!)
  22. (sum-of-squares r2 r)))
  23. ;; Exercise 1.3. Define a procedure that takes three numbers as arguments and
  24. ;; returns the sum of the squares of the two larger numbers.
  25. (define (f3 x y z)
  26. ;; (if (< x y)
  27. ;;
  28. ;;(if (< x z)
  29. ;; (sum-of-squares y z)
  30. ;; (sum-of-squares y (if (< y z) z))))
  31. (cond ((<= x y z) (sum-of-squares y z))
  32. ((<= x z y)(sum-of-squares y z))
  33. ((<= y x z)(sum-of-squares x z))
  34. ((<= y z x)(sum-of-squares x z))
  35. ((<= z x y)(sum-of-squares x y))
  36. ((<= z y x)(sum-of-squares x y))
  37. (else (error "wrong"))))
  38. (define (mylength lis)
  39. (cond ((null? lis)
  40. 0)
  41. (else
  42. (+ 1 (mylength (cdr lis))))))
  43. ;; f3, 1,2,3 => 13
  44. (f3
  45. 1 2 3)
  46. (sum-of-squares 2 3)