————————————————————————————————
;;; Ex-02-01:
;;;
;;; An Impossible 3-LISP Definition, alas:
;;;
(define SQUARE-ROOT ; This is not 3-LISP!
(lambda [n]
(the x ; "(the e1 e2)" is supposed to mean "the e1 such that e2".
(= n (* x x)))))
;;; What one can have, is to turn this into a predicate:
(define SQUARE-ROOT
(lambda [x n]
(= n (* x x))))
;;; but this is quite different!
————————————————————————————————
;;; Ex-02-02:
;;;
;;; A Simple Recursive (Functional) Definition:
;;;
(define FACTORIAL1
(lambda [n]
(if (= n 0)
1
(* n (factorial1 (- n 1))))))
———————————
;;;
;;; An Imperative Definition (in a BASIC-like language):
;;;
(define FACTORIAL2
(lambda [n]
(begin-basic (set counter 0) ; This is not 3-LISP!
(set answer 1)
loop (if (= counter n)
(return answer))
(set counter (+ 1 counter))
(set answer (* counter answer))
(go loop))))
———————————
;;;
;;; A Legitimate Iterative Definition:
;;;
(define FACTORIAL3
(lambda [n]
(factorial3-helper 0 n 1)))
(define FACTORIAL3-HELPER
(lambda [i n acc]
(if (= i n)
acc
(factorial3-helper (+ i 1)
n
(* i acc)))))
———————————————————————————————————————————
;;; Ex-02-03:
;;;
;;; A Proecedure for testing whether a tree is balanced:
;;;
;;; Trivial tree: nodes are either leaves (say, strings or numbers), or two-element
;;; sequences of descendents.
(define BALANCED
(lambda [tree]
(if (not (sequence tree))
[$true 1]
(let [[check-left (balanced (first tree))]
[check-right (balanced (second tree))]]
[(and (first check-left)
(first check-right)
(= (second check-left) (second check-right)))
(+ 1 (second check-left))]))))