#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
0 B
|👍
/👎
0 B
|👍
/👎