Exercise 1.3

Read Exercise 1.3 ~ Solution


(define (sum-larger-squares a b c)
  (cond ((and (<= a b) (<= a c)) (+ (* b b) (* c c)))
        ((and (<= b a) (<= b c)) (+ (* a a) (* c c)))
        (else (+ (* a a) (* b b)))))

(sum-larger-squares 5 3 2)
; 34
(sum-larger-squares 5 2 3)
; 34
(sum-larger-squares 2 3 5)
; 34
(sum-larger-squares 8 -3 -27)
; 73

6 thoughts on “Exercise 1.3

  1. (define (smaller a b)
    (if (< a b)
    a
    b))
    (define (square a) (* a a))
    (define (smallest a b c) (smaller a (smaller b c)))
    (define (sum_of_square_of_two_larger a b c) (- (+ (square a) (square b) (square c)) (square (smallest a b c))))

    1. (define (square x)
      (* x x))

      (define (sum-of-squares x y)
      (+ (square x) (square y)))

      (define (sum-sq-largest-nums x y z)
      (if (> x y)
      (sum-of-squares x (if (> y z) y z))
      (sum-of-squares y (if (> x z) x z))))

  2. (define (square a) (* a a))

    (define (sum-square a b)
    (+ (square a) (square b)))

    (define (max a b) (if (> a b) a b))

    (define (sum-larger-squares a b c)
    (sum-square (max a b) (max b c)))

  3. (define (take n l acc)
    (if (>= (length acc) n)
    acc
    (take n (cdr l) (append acc (list (car l))))))

    (define (larger a b)
    (if (> a b)
    a
    b))

    (define (sort key-func l acc l_)
    (if (>= (length acc) (length l_))
    acc
    (let ([largest (fold larger (cdr l) (car l))])
    (sort key-func (remove-first largest l) (append acc (list largest)) l_))))

    (define (remove-first v l)
    (if (equal? (car l) v)
    (cdr l)
    (cons (car l) (remove-first v (cdr l)))))

    (define (sum-of-squares l)
    (sum(map square l)))

    (define (square x) (* x x))

    (define (sum l)
    (fold + l 0))

    (define (fold f l acc)
    (if (null? l)
    acc
    (fold f (cdr l) (f acc (car l)))))

    (define (take-largest-two-then-sum-squares l)
    (sum-of-squares (sort > (take 2 l []) ‘() (take 2 l []))))

Leave a comment