;; Caltech CS1 Fall 2007
;; Recursion
;; Scheme code used in Lecture 3 (10/8/07)
;; mvanier@cs.caltech.edu

;; New special form: if
;; General form:
;;  (if test-expression true-case else-case)
(if (> 3 4) 3 4)
(if (> a b) a b)

;; Evaluation rule for if special form
;; To evaluate an if-expression:
;;  1. Evaluate the boolean test-expression
;;  2. If the test-expression evaluates to true (#t)
;;     a. evaluate the true case only
;;     b. otherwise, evaluate the false case only
;;  3. The result of the respective case is the result of the if-expression
;; Important note: only one of the {true case, false case} will be evaluated.

;; Finite sum
(define sum10 (+ 1 2 3 4 5 6 7 8 9 10))
;; Booleans (true or false values)
(> 3 4)
(< 3 4)
(define a 3)
(define b 4)
(define c 3)
(= a b) ;; --> #f (false)
(= a c) ;; --> #t (true)
;; Boolean operators
(define (at-least-two-true? a b c)
  (or (and a b)
      (and b c)
      (and a c)))
;; Using if
(define (max a b) (if (> a b) a b))
;; Sample use
(max 3 2)
;; if returns a value
(/ (if (> a b) a b) (if (> a b) b a))
(define (scale a b) 
  (/ (if (> a b) a b) (if (> a b) b a)))
;; Sample use
(scale 4 2) ;; --> 2
;; First attempt at sum-integers (WRONG)
(define (sum-integers n)
  (+ n (sum-integers (- n 1))))
;; Revised 
(define (sum-integers n)
  (if (= n 0) 
      0
      (+ n (sum-integers (- n 1)))))
;; Mutually recursive functions:
(define (even? n)
  (if (= n 0) #t
       (odd? (- n 1))))
(define (odd? n)
  (if (= n 0) #f
      (even? (- n 1))))
