;sumofsquaresoflargest: # # # -> #
;takes three #'s & returns sum of the squares of the two largest
(define (sumofsquaresoflargest a b c)
(+ (* (largest1 a b c)(largest1 a b c))
(* (largest2 a b c)(largest2 a b c))))
;largest1: # # # -> #
;takes three numbers and returns the largest
(define (largest1 a b c)
(cond [(and (> a b)(> a c)) a]
[(and (> b a)(> b c)) b]
[(and (> c a)(> c b)) c]
[else a]))
;largest2: # # # -> #
;takes three numbers and returns the 2nd largest
(define (largest2 a b c)
(cond [(and (> a b)(< a c)) a]
[(and (> b a)(< b c)) b]
[(and (> c a)(< c b)) c]
[else a]))
;In normal order it would just loop infinitely trying to substitute (p) for (p) looking for a primitive operation to perform. Applicative would evaluate it as 0 by just evaluating (= x 0) as 0 and return 0.
(define (queens board-size)
(define (queen-cols k)
(if (= k 0)
(list empty-board)
(filter
(lambda (positions) (safe? k positions))
(flatmap
(lambda (rest-of-queens)
(map (lambda (new-row)
(adjoin-position new-row k rest-of-queens))
(enumerate-interval 1 board-size)))
(queen-cols (- k 1))))))
(queen-cols board-size))
(define (enumerate-interval i j)
(define (iter i j items)
(if (> i j)
items
(iter i (- j 1) (cons j items))))
(iter i j null))
(define empty-board null)
(define (contains? pred seq)
(not (null? (find pred seq))))
(define (find pred seq)
(cond ((null? seq) null)
((pred (car seq)) (car seq))
(else (find pred (cdr seq)))))
(define make-pos cons)
(define col car)
(define row cdr)
(define (checks? queen new-queen)
(let ((d (- (col new-queen)
(col queen)))
(a (row new-queen))
(b (row queen)))
(or (= a b) ; check same row
(= a (- b d)) ; "north-east" diagonal
(= a (+ b d))))) ; "south-east" diagonal
; given the list of positions of all k queens is the k-th placed in
; a safe position? queens 1 .. k-1 are assumed to be in safe positions
(define (safe? k positions)
(let ((added (car positions))
(rest (cdr positions)))
(not (contains? (lambda (queen) (checks? queen added))
rest))))
; add the k-th queen on the position new-row to the rest of the queens
(define (adjoin-position new-row k rest-of-queens)
(cons (make-pos k new-row) rest-of-queens))
(display (queens 6)) (newline)
Would the Sussman approve my solution dear /prog/?
I have to warn you thou. I write my exercises in VIM.
Name:
Anonymous2008-08-31 16:02
>>7
Apparently he is trying to bring back Superbraces.