timothy235 icon

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

timothy235 | PRO | 12/19/24 01:06:40 AM UTC (Edited) | 0 ⭐ | 7272 👁️ | Never ⏰ | []
Racket |

1.28 KB

|

None

|

0 👍

/

0 👎

#lang racket
 
;;;;;;;;;;
;; 4.25 ;;
;;;;;;;;;;
 
(define (my-unless condition usual-value exceptional-value)
  (if condition exceptional-value usual-value))
 
(define (factorial n)
  (my-unless (= n 1)
             (* n (factorial (sub1 n)))
             1))
 
;; When evaluating (factorial 5), the final recursive call will be
;; (my-unless 1 (* 1 (factorial 0)) 1).  Because of eager evaluation, Scheme will try
;; to evaluate (factorial 0) and fall into an infinite loop.
 
;; But lazy evaluation would not evaluate the unneeded usual-value and terminate as
;; expected, returning 120.
 
(define (lazy-my-unless condition delayed-usual-value exceptional-value)
  (if condition
    exceptional-value
    (force delayed-usual-value)))
 
(define (factorial2 n)
  (lazy-my-unless (= n 1)
             (delay (* n (factorial2 (sub1 n))))
             1))
 
(factorial2 5)
;; 120
 
;;;;;;;;;;
;; 4.26 ;;
;;;;;;;;;;
 
;; Unless would be implemented exactly like if but with branches reversed.
 
;; If you implemented unless as a special form, you could not pass it to map like you
;; could a procedure.  For example, you cannot pass if to map:
 
(define bools (list false true false))
(define xs '(a b c))
(define ys '(1 2 3))
 
;; (map if bools xs ys)
;; ;; . if: bad syntax in: if

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎