Advertisement
timothy235

sicp-4-2-1-normal-order-and-applicative-order

Mar 17th, 2017
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Racket 1.29 KB | None | 0 0
  1. #lang racket
  2.  
  3. ;;;;;;;;;;
  4. ;; 4.25 ;;
  5. ;;;;;;;;;;
  6.  
  7. (define (my-unless condition usual-value exceptional-value)
  8.   (if condition exceptional-value usual-value))
  9.  
  10. (define (factorial n)
  11.   (my-unless (= n 1)
  12.              (* n (factorial (sub1 n)))
  13.              1))
  14.  
  15. ;; When evaluating (factorial 5), the final recursive call will be
  16. ;; (my-unless 1 (* 1 (factorial 0)) 1).  Because of eager evaluation, Scheme will try
  17. ;; to evaluate (factorial 0) and fall into an infinite loop.
  18.  
  19. ;; But lazy evaluation would not evaluate the unneeded usual-value and terminate as
  20. ;; expected, returning 120.
  21.  
  22. (define (lazy-my-unless condition delayed-usual-value exceptional-value)
  23.   (if condition
  24.     exceptional-value
  25.     (force delayed-usual-value)))
  26.  
  27. (define (factorial2 n)
  28.   (lazy-my-unless (= n 1)
  29.              (delay (* n (factorial2 (sub1 n))))
  30.              1))
  31.  
  32. (factorial2 5)
  33. ;; 120
  34.  
  35. ;;;;;;;;;;
  36. ;; 4.26 ;;
  37. ;;;;;;;;;;
  38.  
  39. ;; Unless would be implemented exactly like if but with branches reversed.
  40.  
  41. ;; If you implemented unless as a special form, you could not pass it to map like you
  42. ;; could a procedure.  For example, you cannot pass if to map:
  43.  
  44. (define bools (list false true false))
  45. (define xs '(a b c))
  46. (define ys '(1 2 3))
  47.  
  48. ;; (map if bools xs ys)
  49. ;; ;; . if: bad syntax in: if
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement