Scheme practice

Final 15 exam questions

F.01 addAnA, duplicate, whatIsThis (Lab 9 Q1)

Write three one-argument functions to be used with map:

  • addAnA conses an a onto its argument.
  • duplicate turns (x) into (x x).
  • whatIsThis: work out the rule from the examples.

None of them are recursive. (Same as Lab 9 Question 1 on Moodle.)

(map addAnA '((1) (2) (3)))          ⇒ ((a 1) (a 2) (a 3))
(map duplicate '((a) (b) (c)))       ⇒ ((a a) (b b) (c c))
(map duplicate '((1) (4) (9)))       ⇒ ((1 1) (4 4) (9 9))
(map whatIsThis '(4 2 3 2 6 10 1) )  ⇒ (3 1 4 1 5 9 2)
(map whatIsThis '(4 6 8 5 7 9) )     ⇒ (3 5 7 6 8 10)
Show answer

None of these need recursion: map does the walking, so each function only deals with ONE element. addAnA conses 'a on the front; duplicate conses the element's own car onto it, so (x) becomes (x x). For whatIsThis, line up inputs and outputs: every even number goes down by 1 and every odd number goes up by 1.

(define addAnA
  (lambda (X)
    (cons 'a X)))

(define duplicate
  (lambda (X)
    (cons (car X) X)))

;; even numbers go down by 1, odd numbers go up by 1
(define whatIsThis
  (lambda (N)
    (cond ((even? N) (- N 1))
          (else (+ N 1)))))

F.02 howMany and evenList? (Lab 9 Q2)

Write howMany, which takes a function test? and a list L and returns a list of two numbers: how many elements of L pass test?, then how many fail it. Using filter and length is easiest.

Also write evenList?, which returns #t if a list has an even number of elements. (Same as Lab 9 Question 2 on Moodle.)

(howMany even? '(1 5 2 4 6 3 8))            ⇒ (4 3)
(howMany negative? '(1 -5 -2 4 6 3 8))      ⇒ (2 5)
(howMany evenList? '((1 2 3) (4 5) (6 7)))  ⇒ (2 1)
(howMany evenList? '((1 2) () ()))          ⇒ (3 0)
(howMany evenList? '())                     ⇒ (0 0)
Show answer

(filter test? L) keeps exactly the passing elements, so its length is the first count. For the second count, filter with a lambda that negates the test. (not test?) would be wrong, because test? is a function, not a true/false value. evenList? just checks (even? (length L)).

(define howMany
  (lambda (test? L)
    (list (length (filter test? L))
          (length (filter (lambda (x) (not (test? x))) L)))))

(define evenList?
  (lambda (L)
    (even? (length L))))

F.03 average (Lab 10 Q1)

Write average, which takes AS MANY ARGUMENTS as the caller wants and returns their average. The arguments are NOT in a list. Use the variable-arity form of lambda, plus apply and length. Does it need to be recursive? (Same as Lab 10 Question 1 on Moodle.)

(average 3 4 5)      ⇒ 4
(average 1 2 3 4 5)  ⇒ 3
(average 10)         ⇒ 10
(average -6 2)       ⇒ -2

Not allowed: foldl or foldr.

Show answer

With (lambda args ...) (no brackets), every argument lands in ONE list called args. Now it's an ordinary list problem: (apply + args) spreads the list into + to get the total, and length gives the count. No recursion needed.

;; (lambda args ...) with no brackets: args is a list of all the arguments
(define average
  (lambda args
    (/ (apply + args) (length args))))

F.04 power (Lab 10 Q2)

Write power, which takes AS MANY ARGUMENTS as the caller wants and returns the first number to the power of (the second to the power of (the third …)). (power 4 3 2) = 4^(3^2) = 262144. Use expt. It must be recursive. The base case is no arguments: (power) = 1. Use apply for the recursive call. (Same as Lab 10 Question 2 on Moodle.)

(power 4 3 2)  ⇒ 262144
(power 2 3 2)  ⇒ 512
(power)        ⇒ 1
(power 7)      ⇒ 7
Show answer

The base case is no arguments at all: args is '() and the answer is 1. Otherwise raise (car args) to the power of the REST. The rest is a list, so you must call (apply power (cdr args)). (power (cdr args)) would pass the whole list as a single argument.

(define power
  (lambda args
    (cond ((null? args) 1)
          (else (expt (car args)
                      (apply power (cdr args)))))))

F.05 pickOne (Lab 10 Q3)

Write pickOne, which takes AS MANY ARGUMENTS as the caller wants and returns one of them at random. (random N) gives an integer from 0 to N−1. list-ref (or your getElement) will help. (Same as Lab 10 Question 3 on Moodle; on the practice site the tests check the answer is always one of the arguments and that every argument eventually turns up.)

(if (member (pickOne 'cut-red-wire 'cut-blue-wire 'cut-yellow-wire) '(cut-red-wire cut-blue-wire cut-yellow-wire)) #t #f)
  ⇒ #t
(if (member (pickOne 'work 'rest 'play) '(work rest play)) #t #f)
  ⇒ #t
(pickOne 'only)
  ⇒ only
(let loop ((i 0) (seen '())) (if (= i 200) (length seen) (let ((x (pickOne 'work 'rest 'play))) (loop (+ i 1) (if (member x seen) seen (cons x seen))))))
  ⇒ 3
Show answer

Collect the arguments into a list, pick a random index from 0 to length−1 with (random (length args)), and fetch it with list-ref, which counts from 0. Because random never returns N itself, the index is always valid.

(define pickOne
  (lambda args
    (list-ref args (random (length args)))))

F.06 byParity

byParity takes two one-argument functions, forEven and forOdd, and returns a function of one number. That function calls forEven on the number if it's even, and forOdd if it's odd.

This is lab 9's whatIsThis, built from two functions:

(map (byParity (lambda (x) (- x 1)) (lambda (x) (+ x 1))) '(4 2 3 2 6 10 1)) → (3 1 4 1 5 9 2)

The returned function has to remember forEven and forOdd after byParity has finished. That's the closure.

(map (byParity (lambda (x) (- x 1)) (lambda (x) (+ x 1))) '(4 2 3 2 6 10 1))
  ⇒ (3 1 4 1 5 9 2)
(map (byParity (lambda (x) (* x 10)) -) '(1 2 3))
  ⇒ (-1 20 -3)
((byParity list sqrt) 9)
  ⇒ 3
((byParity list sqrt) 4)
  ⇒ (4)
(map (byParity car cdr) '())
  ⇒ ()
(let ((f (byParity (lambda (x) (quotient x 2)) (lambda (x) (+ (* 3 x) 1))))) (list (f 6) (f 3) (f (f 3))))
  ⇒ (3 10 5)
Show answer

A closure: byParity returns a new lambda that still remembers forEven and forOdd after byParity has finished. When the returned function gets a number, it just chooses which of the remembered functions to call.

(define byParity
  (lambda (forEven forOdd)
    (lambda (n)                          ; the closure remembers forEven and forOdd
      (cond ((even? n) (forEven n))
            (else (forOdd n))))))

F.07 prefixWith

prefixWith takes any number of things and returns a function of one list. That function puts all those things on the front of the list, in the same order:

((prefixWith 'x 'y) '(1 2)) → (x y 1 2)

With one thing, it's lab 9's addAnA:

(map (prefixWith 'a) '((1) (2) (3))) → ((a 1) (a 2) (a 3))

(map (prefixWith 'a) '((1) (2) (3)))
  ⇒ ((a 1) (a 2) (a 3))
((prefixWith 'x 'y) '(1 2))
  ⇒ (x y 1 2)
((prefixWith) '(1 2))
  ⇒ (1 2)
((prefixWith 1 2 3) '())
  ⇒ (1 2 3)
((prefixWith '(a)) '(b))
  ⇒ ((a) b)
(let ((addAnA (prefixWith 'a))) (map addAnA (map addAnA '((1) ()))))
  ⇒ ((a a 1) (a a))
Show answer

Two levels. The outer (lambda things ...) collects any number of things into a list. The inner lambda takes the list L and appends the remembered things in front. With no things, append of '() and L just gives L.

(define prefixWith
  (lambda things                         ; things is a list of every argument
    (lambda (L)
      (append things L))))

F.08 copier

copier takes a whole number n ≥ 0 and returns a function. That function takes a one-element list like (a) and returns a list holding that element n times:

((copier 3) '(x)) → (x x x)

With n = 2 it's lab 9's duplicate:

(map (copier 2) '((a) (b) (c))) → ((a a) (b b) (c c))

(map (copier 2) '((a) (b) (c)))
  ⇒ ((a a) (b b) (c c))
((copier 3) '(x))
  ⇒ (x x x)
((copier 0) '(x))
  ⇒ ()
((copier 1) '((1 2)))
  ⇒ ((1 2))
(map (copier 4) '((1) (9)))
  ⇒ ((1 1 1 1) (9 9 9 9))
(let ((triple (copier 3))) (list (triple '(a)) (triple '(b))))
  ⇒ ((a a a) (b b b))

Not allowed: make-list or build-list.

Show answer

copier remembers n and returns a function. That function takes (x) and builds a list of n copies of (car L) with a small counting helper, because make-list is banned. The helper's base case is 0 copies: '().

;; helper: a list of k copies of x
(define repeat
  (lambda (x k)
    (cond ((= k 0) '())
          (else (cons x (repeat x (- k 1)))))))

(define copier
  (lambda (n)
    (lambda (L)                          ; remembers n
      (repeat (car L) n))))

F.09 averageWith

averageWith takes a one-argument function f and returns a function that takes one or more numbers. It returns the average of f applied to each of them:

((averageWith abs) -3 5 -4) → 4 (the average of 3, 5 and 4)

With a function that changes nothing, it's lab 10's average:

((averageWith (lambda (x) x)) 3 4 5) → 4

(Every test divides evenly.)

((averageWith abs) -3 5 -4)
  ⇒ 4
((averageWith (lambda (x) x)) 3 4 5)
  ⇒ 4
((averageWith (lambda (x) (* x x))) 1 3)
  ⇒ 5
((averageWith length) '(a) '(b c d))
  ⇒ 2
((averageWith abs) -7)
  ⇒ 7
(let ((avgSq (averageWith (lambda (x) (* x x))))) (list (avgSq 2) (avgSq 2 4)))
  ⇒ (4 10)

Not allowed: foldl or foldr.

Show answer

The returned function is variable-arity: (lambda args ...). map f over the arguments first, then average the results with apply + and length. f is remembered from the outer call.

(define averageWith
  (lambda (f)
    (lambda args                         ; any number of arguments
      (/ (apply + (map f args))
         (length args)))))

F.10 chooser

chooser takes one or more things and returns a function of no arguments. Every time that function is called, it returns one of the things, picked at random:

(define coin (chooser 'heads 'tails))
(coin) ; heads or tails
(coin) ; heads or tails again, picked fresh

It has to pick again on every call, not once when the function is made.

(if (member ((chooser 'heads 'tails)) '(heads tails)) #t #f)
  ⇒ #t
((chooser 'only))
  ⇒ only
(procedure? (chooser 1 2))
  ⇒ #t
(let ((c (chooser 'rock 'paper 'scissors))) (let loop ((i 0) (seen '())) (if (= i 200) (length seen) (let ((x (c))) (loop (+ i 1) (if (member x seen) seen (cons x seen)))))))
  ⇒ 3
Show answer

The key point: the random call must be INSIDE the returned (lambda () ...). Then it runs again every time you call the chooser. If you picked outside it, you'd pick once and return the same thing forever.

(define chooser
  (lambda things
    (lambda ()                           ; random is called inside, so every call picks fresh
      (list-ref things (random (length things))))))

F.11 tally

tally takes a test (a function that returns #t or #f) and returns a function that takes any number of arguments. It returns a list of two numbers: how many of the arguments pass the test, then how many fail it.

((tally even?) 1 5 2 4 6 3 8) → (4 3)

It's lab 9's howMany, except the test is remembered and the values come as separate arguments, not a list.

((tally even?) 1 5 2 4 6 3 8)                         ⇒ (4 3)
((tally negative?) 1 -5 -2 4)                         ⇒ (2 2)
((tally even?))                                       ⇒ (0 0)
((tally null?) '() '(a) '())                          ⇒ (2 1)
(let ((t (tally symbol?))) (list (t 'a 1 'b) (t 2)))  ⇒ ((2 1) (0 1))
Show answer

Lab 9's howMany, reshaped: the outer lambda remembers test?, the inner (lambda args ...) gets the values. Count the passes with filter, and the failures are simply the total minus the passes.

(define tally
  (lambda (test?)
    (lambda args
      (let ((pass (length (filter test? args))))
        (list pass (- (length args) pass))))))

F.12 howManyEach

howManyEach takes any number of tests and returns a function of one list L. That function returns a list with one number per test, in the same order: how many elements of L pass that test.

((howManyEach even? negative?) '(1 -2 4 -3)) → (2 2)

(-2 and 4 are even; -2 and -3 are negative.)

((howManyEach even? negative?) '(1 -2 4 -3))
  ⇒ (2 2)
((howManyEach even? odd? zero?) '(0 1 2 3 4))
  ⇒ (3 2 1)
((howManyEach) '(1 2 3))
  ⇒ ()
((howManyEach number? symbol?) '())
  ⇒ (0 0)
(let ((h (howManyEach null? pair?))) (list (h '(() (a) ())) (h '((1 2)))))
  ⇒ ((2 1) (0 1))
Show answer

tests is a list of predicates. For each test, count how many elements of L pass it. That's "do something to every test", so map over tests with a lambda that does (length (filter test? L)).

(define howManyEach
  (lambda tests
    (lambda (L)
      (map (lambda (test?) (length (filter test? L)))
           tests))))

F.13 relativeTo

relativeTo takes one or more numbers and returns a function of one number y. That function returns how far y is above the average of those numbers (y minus the average; negative if it's below):

((relativeTo 2 4 6) 10) → 6 (the average is 4)
((relativeTo 2 4 6) 1) → -3

(Every test divides evenly.)

((relativeTo 2 4 6) 10)                                ⇒ 6
((relativeTo 2 4 6) 1)                                 ⇒ -3
((relativeTo 5) 5)                                     ⇒ 0
(map (relativeTo 10 20) '(15 30 0))                    ⇒ (0 15 -15)
(let ((f (relativeTo 1 2 3 4 5))) (list (f 3) (f 8)))  ⇒ (0 5)
Show answer

Work out the average ONCE, in a let, outside the returned lambda. The closure remembers that number, and each call just subtracts it from y.

(define relativeTo
  (lambda nums
    (let ((avg (/ (apply + nums) (length nums))))   ; worked out once, remembered
      (lambda (y)
        (- y avg)))))

F.14 foldArgs

foldArgs takes a two-argument function op and a starting value start. It returns a function that takes any number of arguments and combines them from the right:

((foldArgs op start) a b c) means (op a (op b (op c start)))

With no arguments, you get start.

With expt and 1, it's lab 10's power:

((foldArgs expt 1) 4 3 2) → 262144

((foldArgs expt 1) 4 3 2)
  ⇒ 262144
((foldArgs expt 1))
  ⇒ 1
((foldArgs - 0) 10 4 1)
  ⇒ 7
((foldArgs cons '()) 1 2 3)
  ⇒ (1 2 3)
((foldArgs list 'end) 'a 'b)
  ⇒ (a (b end))
(let ((power (foldArgs expt 1))) (list (power 2 3 2) (power 5)))
  ⇒ (512 5)

Not allowed: foldl or foldr.

Show answer

Name the inner variable-arity function, here combine, so it can call itself. The base case is no arguments, which gives start. Otherwise it combines (car args) with the result for the rest, using apply to spread the rest back out. This mirrors power exactly.

(define foldArgs
  (lambda (op start)
    (define combine                      ; named so it can call itself
      (lambda args
        (cond ((null? args) start)
              (else (op (car args)
                        (apply combine (cdr args)))))))
    combine))

F.15 runningTally

runningTally takes a test and returns a function that takes any number of arguments. Every call adds its arguments to running totals, and returns the totals so far as a list: how many passed the test, then how many failed.

(define t (runningTally even?))
(t 1 2 3) ; (1 2)
(t 4)     ; (2 2)
(t)       ; (2 2) no arguments: adds nothing, just reports

Two functions made by runningTally keep separate totals. You need set! (see makeCounter in Scope & Closures).

(let ((t (runningTally even?))) (t 1 2 3))
  ⇒ (1 2)
(let ((t (runningTally even?))) (t 1 2 3) (t 4))
  ⇒ (2 2)
((runningTally even?))
  ⇒ (0 0)
(let ((t (runningTally even?))) (t 2) (t))
  ⇒ (1 0)
(let* ((t (runningTally symbol?)) (x (t 'a 1)) (y (t 'b 'c))) (list x y))
  ⇒ ((1 1) (3 1))
(let ((a (runningTally negative?)) (b (runningTally negative?))) (a -1 -2) (b 5) (list (a) (b)))
  ⇒ ((2 0) (0 1))
Show answer

The two counters live in a let that runs each time runningTally is called, so every tally function gets its OWN pair. Inside, set! updates them before the totals are returned. Calling with no arguments adds 0 and 0, so it just reports.

(define runningTally
  (lambda (test?)
    (let ((passed 0)                     ; fresh totals for each function made
          (failed 0))
      (lambda args
        (let ((p (length (filter test? args))))
          (set! passed (+ passed p))
          (set! failed (+ failed (- (length args) p)))
          (list passed failed))))))

Easy

sumList

Write sumList, which takes a list of numbers L and returns their sum.

(sumList '(1 2 3))   ⇒ 6
(sumList '(10))      ⇒ 10
(sumList '())        ⇒ 0
(sumList '(5 -2 7))  ⇒ 10

Not allowed: apply, foldl or foldr.

Show answer

The classic shape: the empty list sums to 0, since adding 0 changes nothing. Otherwise add the first number to the sum of the rest.

(define sumList
  (lambda (L)
    (cond ((null? L) 0)
          (else (+ (car L) (sumList (cdr L)))))))

countOf

Write countOf, which returns how many times X appears in the list L.

X can be a number, a symbol or even a list, so compare with equal?.

(countOf 'a '(a b a c a))          ⇒ 3
(countOf 3 '(1 2 4))               ⇒ 0
(countOf 'x '())                   ⇒ 0
(countOf '(1 2) '((1 2) 3 (1 2)))  ⇒ 2

Not allowed: count, filter, foldl, foldr or remove*.

Show answer

Three cases. Empty list: 0. The first element matches: 1 plus the count in the rest. Otherwise: just the count in the rest. Use equal?, because X can be a list.

(define countOf
  (lambda (X L)
    (cond ((null? L) 0)
          ((equal? X (car L)) (+ 1 (countOf X (cdr L))))
          (else (countOf X (cdr L))))))

myLast

Write myLast, which returns the last element of a non-empty list L.

(myLast '(1 2 3))        ⇒ 3
(myLast '(a))            ⇒ a
(myLast '((1 2) (3 4)))  ⇒ (3 4)
(myLast '(x y))          ⇒ y

Not allowed: last, reverse, last-pair, take-right or list-ref.

Show answer

Stop when there's exactly one element left, (null? (cdr L)), and return it. Otherwise throw away the first element and keep going.

(define myLast
  (lambda (L)
    (cond ((null? (cdr L)) (car L))
          (else (myLast (cdr L))))))

doubleAll

Write doubleAll, which takes a list of numbers and returns a new list with every number doubled.

(doubleAll '(1 2 3))  ⇒ (2 4 6)
(doubleAll '())       ⇒ ()
(doubleAll '(0 -5))   ⇒ (0 -10)
(doubleAll '(7))      ⇒ (14)

Not allowed: map, foldr, foldl or append-map.

Show answer

Building a new list: the empty list gives '(). Otherwise cons the doubled first element onto the doubled rest.

(define doubleAll
  (lambda (L)
    (cond ((null? L) '())
          (else (cons (* 2 (car L)) (doubleAll (cdr L)))))))

removeAll

Write removeAll, which returns L with every occurrence of X removed. Everything else stays in its original order.

(removeAll 'a '(a b a c))  ⇒ (b c)
(removeAll 3 '(1 2))       ⇒ (1 2)
(removeAll 'z '())         ⇒ ()
(removeAll 1 '(1 1 1))     ⇒ ()

Not allowed: filter, remove, remove*, remq*, remv*, filter-not, foldr, foldl, remq or remv.

Show answer

When the first element matches, skip it by just recursing. Otherwise keep it with cons. The base case '() ends the new list.

(define removeAll
  (lambda (X L)
    (cond ((null? L) '())
          ((equal? X (car L)) (removeAll X (cdr L)))
          (else (cons (car L) (removeAll X (cdr L)))))))

isMember

Write isMember, which returns #t if X appears in L and #f otherwise.

(isMember 'c '(a b c))      ⇒ #t
(isMember 'z '(a b))        ⇒ #f
(isMember 1 '())            ⇒ #f
(isMember '(2) '(1 (2) 3))  ⇒ #t

Not allowed: member, memq, memv, memf, findf, index-of or ormap.

Show answer

Returns as soon as it knows. Empty list: #f. First element matches: #t. Otherwise search the rest.

(define isMember
  (lambda (X L)
    (cond ((null? L) #f)
          ((equal? X (car L)) #t)
          (else (isMember X (cdr L))))))

countDown

Write countDown, which takes a whole number N ≥ 0 and returns the list (N N-1 … 2 1). (countDown 0) is the empty list.

(countDown 3)  ⇒ (3 2 1)
(countDown 1)  ⇒ (1)
(countDown 0)  ⇒ ()
(countDown 5)  ⇒ (5 4 3 2 1)

Not allowed: range, build-list or inclusive-range.

Show answer

Recursion on a number, not a list: 0 gives '(). Otherwise cons N onto the countdown from N−1.

(define countDown
  (lambda (N)
    (cond ((= N 0) '())
          (else (cons N (countDown (- N 1)))))))

sumDigits

Write sumDigits, which takes a whole number N ≥ 0 and returns the sum of its digits.

(sumDigits 327)   ⇒ 12
(sumDigits 5)     ⇒ 5
(sumDigits 0)     ⇒ 0
(sumDigits 1009)  ⇒ 10
Show answer

(remainder N 10) is the last digit and (quotient N 10) chops it off. A single digit (N < 10) is its own sum, and that also covers 0.

(define sumDigits
  (lambda (N)
    (cond ((< N 10) N)
          (else (+ (remainder N 10)                ; last digit
                   (sumDigits (quotient N 10))))))) ; the rest

myNth

Write myNth, which returns the element at position N of L, counting from 0. You can assume N is always a valid position.

(myNth 0 '(a b c))        ⇒ a
(myNth 2 '(a b c))        ⇒ c
(myNth 1 '((1) (2) (3)))  ⇒ (2)
(myNth 3 '(5 6 7 8))      ⇒ 8

Not allowed: list-ref, list-tail, drop or take.

Show answer

Count down N while walking down L. When N hits 0, the element you want is the car.

(define myNth
  (lambda (N L)
    (cond ((= N 0) (car L))
          (else (myNth (- N 1) (cdr L))))))

allEven

Write allEven, which returns #t if every number in L is even, and #f otherwise. For the empty list the answer is #t: there's no number in it that breaks the rule.

(allEven '(2 4 6))  ⇒ #t
(allEven '(2 3 4))  ⇒ #f
(allEven '())       ⇒ #t
(allEven '(1))      ⇒ #f
(allEven '(0 -2))   ⇒ #t

Not allowed: andmap, filter, count or ormap.

Show answer

#t for the empty list (nothing breaks the rule). As soon as one element isn't even, the answer is #f. Otherwise check the rest.

(define allEven
  (lambda (L)
    (cond ((null? L) #t)
          ((even? (car L)) (allEven (cdr L)))
          (else #f))))

productList

Write productList, which returns the product of all the numbers in L.

(productList '(2 3 4))  ⇒ 24
(productList '(7))      ⇒ 7
(productList '())       ⇒ 1
(productList '(5 0 2))  ⇒ 0

Not allowed: foldr, foldl or apply.

Show answer

Like sumList, but the empty product is 1, because multiplying by 1 changes nothing. 0 would make every answer 0.

(define productList
  (lambda (L)
    (cond ((null? L) 1)
          (else (* (car L) (productList (cdr L)))))))

countEvens

Write countEvens, which returns how many even numbers are in L.

(countEvens '(1 2 3 4))  ⇒ 2
(countEvens '(1 3 5))    ⇒ 0
(countEvens '())         ⇒ 0
(countEvens '(0 -2 8))   ⇒ 3

Not allowed: foldr, foldl, apply, count or filter.

Show answer

Count with a condition: add 1 when the first element is even, add nothing otherwise. The empty list counts 0.

(define countEvens
  (lambda (L)
    (cond ((null? L) 0)
          ((even? (car L)) (+ 1 (countEvens (cdr L))))
          (else (countEvens (cdr L))))))

myLength

Write myLength, which returns how many elements are in L. The built-in length is off-limits.

(myLength '(a b c))          ⇒ 3
(myLength '())               ⇒ 0
(myLength '((1 2) (3 4 5)))  ⇒ 2
(myLength '(x))              ⇒ 1

Not allowed: foldr, foldl, apply or length.

Show answer

Every element is worth 1, whatever it is, even a list: 1 + the length of the rest. The empty list has length 0.

(define myLength
  (lambda (L)
    (cond ((null? L) 0)
          (else (+ 1 (myLength (cdr L)))))))

addOneAll

Write addOneAll, which returns a new list with 1 added to every number in L.

(addOneAll '(1 2 3))  ⇒ (2 3 4)
(addOneAll '())       ⇒ ()
(addOneAll '(-1 0))   ⇒ (0 1)
(addOneAll '(99))     ⇒ (100)

Not allowed: foldr, foldl, apply or map.

Show answer

Same shape as doubleAll: cons (first + 1) onto the result for the rest.

(define addOneAll
  (lambda (L)
    (cond ((null? L) '())
          (else (cons (+ 1 (car L)) (addOneAll (cdr L)))))))

sumTo

Write sumTo, which takes a whole number N ≥ 0 and returns 1 + 2 + … + N.

(sumTo 4)   ⇒ 10
(sumTo 1)   ⇒ 1
(sumTo 0)   ⇒ 0
(sumTo 10)  ⇒ 55
Show answer

Recursion on the number: 0 sums to 0. Otherwise N + sumTo(N−1).

(define sumTo
  (lambda (N)
    (cond ((= N 0) 0)
          (else (+ N (sumTo (- N 1)))))))

factorial

Write factorial, which takes a whole number N ≥ 0 and returns N! = 1 × 2 × … × N. By definition, 0! is 1.

(factorial 5)   ⇒ 120
(factorial 0)   ⇒ 1
(factorial 1)   ⇒ 1
(factorial 10)  ⇒ 3628800
Show answer

0! is 1 by definition, and that's the base case. Otherwise N × (N−1)!.

(define factorial
  (lambda (N)
    (cond ((= N 0) 1)
          (else (* N (factorial (- N 1)))))))

power (two arguments)

Write power, which returns B raised to the whole-number power E ≥ 0. The built-in expt is off-limits.

(power 2 5)   ⇒ 32
(power 7 0)   ⇒ 1
(power 3 1)   ⇒ 3
(power -2 3)  ⇒ -8

Not allowed: expt, exp, sqr or apply.

Show answer

B⁰ = 1 is the base case. Each step multiplies one more B: B × B^(E−1).

(define power
  (lambda (B E)
    (cond ((= E 0) 1)
          (else (* B (power B (- E 1)))))))

countZeros

Write countZeros, which returns how many times the number 0 appears in L.

(countZeros '(0 1 0 2))  ⇒ 2
(countZeros '())         ⇒ 0
(countZeros '(4 5))      ⇒ 0
(countZeros '(0 0 0))    ⇒ 3

Not allowed: foldr, foldl, apply, count or filter.

Show answer

Count with a condition: compare the first element with 0 using =.

(define countZeros
  (lambda (L)
    (cond ((null? L) 0)
          ((= (car L) 0) (+ 1 (countZeros (cdr L))))
          (else (countZeros (cdr L))))))

negateAll

Write negateAll, which returns a new list where every number in L has its sign flipped.

(negateAll '(1 -2 3))  ⇒ (-1 2 -3)
(negateAll '())        ⇒ ()
(negateAll '(0))       ⇒ (0)
(negateAll '(-5 -5))   ⇒ (5 5)

Not allowed: foldr, foldl, apply or map.

Show answer

Build a new list with cons. (- x) with one argument flips the sign.

(define negateAll
  (lambda (L)
    (cond ((null? L) '())
          (else (cons (- (car L)) (negateAll (cdr L)))))))

allPositive

Write allPositive, which returns #t if every number in L is greater than 0, and #f otherwise. An empty list counts as all positive.

(allPositive '(1 2 3))   ⇒ #t
(allPositive '(1 -2 3))  ⇒ #f
(allPositive '())        ⇒ #t
(allPositive '(0))       ⇒ #f

Not allowed: foldr, foldl, apply, andmap, every or filter.

Show answer

Like allEven: empty is #t, the first failure gives #f. Remember 0 is not positive, so use > 0.

(define allPositive
  (lambda (L)
    (cond ((null? L) #t)
          ((> (car L) 0) (allPositive (cdr L)))
          (else #f))))

anyNegative

Write anyNegative, which returns #t if at least one number in L is less than 0, and #f otherwise.

(anyNegative '(3 -1 4))  ⇒ #t
(anyNegative '(1 2))     ⇒ #f
(anyNegative '())        ⇒ #f
(anyNegative '(-7))      ⇒ #t

Not allowed: foldr, foldl, apply, ormap, any, filter or memf.

Show answer

The mirror of allPositive: empty is #f, the first success gives #t.

(define anyNegative
  (lambda (L)
    (cond ((null? L) #f)
          ((< (car L) 0) #t)
          (else (anyNegative (cdr L))))))

squareEach

Write squareEach, which returns a new list containing the square of every number in L.

(squareEach '(1 2 3))  ⇒ (1 4 9)
(squareEach '())       ⇒ ()
(squareEach '(-3))     ⇒ (9)
(squareEach '(0 10))   ⇒ (0 100)

Not allowed: foldr, foldl, apply, map or sqr.

Show answer

Build a new list: cons (x × x) onto the squares of the rest.

(define squareEach
  (lambda (L)
    (cond ((null? L) '())
          (else (cons (* (car L) (car L)) (squareEach (cdr L)))))))

removeFirst

Write removeFirst, which returns L with only the first occurrence of X removed. If X isn't there, return L unchanged.

(removeFirst 'a '(b a c a))  ⇒ (b c a)
(removeFirst 1 '(1 1))       ⇒ (1)
(removeFirst 'z '(a b))      ⇒ (a b)
(removeFirst 'a '())         ⇒ ()

Not allowed: foldr, foldl, apply, remove, remq, remv or filter.

Show answer

Like removeAll, but when you find the match you return (cdr L) straight away. That stops the recursion, so later copies survive.

(define removeFirst
  (lambda (X L)
    (cond ((null? L) '())
          ((equal? X (car L)) (cdr L))   ; found it: drop it and stop
          (else (cons (car L) (removeFirst X (cdr L)))))))

secondLast

Write secondLast, which returns the second-to-last element of L. L always has at least 2 elements.

(secondLast '(a b c d))      ⇒ c
(secondLast '(1 2))          ⇒ 1
(secondLast '(x y z))        ⇒ y
(secondLast '((1) (2) (3)))  ⇒ (2)

Not allowed: foldr, foldl, apply, list-ref, reverse, last, take-right, drop-right or length.

Show answer

Stop when exactly TWO elements are left, (null? (cddr L)), and return the first of them.

(define secondLast
  (lambda (L)
    (cond ((null? (cddr L)) (car L))     ; exactly two left
          (else (secondLast (cdr L))))))

repeatN

Write repeatN, which returns a list containing N copies of X (N ≥ 0).

(repeatN 'a 3)      ⇒ (a a a)
(repeatN 7 1)       ⇒ (7)
(repeatN 'z 0)      ⇒ ()
(repeatN '(1 2) 2)  ⇒ ((1 2) (1 2))

Not allowed: make-list, build-list or apply.

Show answer

Recursion on the count: 0 copies is '(). Otherwise cons X onto N−1 copies.

(define repeatN
  (lambda (X N)
    (cond ((= N 0) '())
          (else (cons X (repeatN X (- N 1)))))))

sumOdds

Write sumOdds, which returns the sum of the odd numbers in L.

(sumOdds '(1 2 3 4 5))  ⇒ 9
(sumOdds '(2 4))        ⇒ 0
(sumOdds '())           ⇒ 0
(sumOdds '(-3 3))       ⇒ 0

Not allowed: foldr, foldl, apply or filter.

Show answer

Add the first element only when it's odd. Negative numbers can be odd too, and odd? handles them.

(define sumOdds
  (lambda (L)
    (cond ((null? L) 0)
          ((odd? (car L)) (+ (car L) (sumOdds (cdr L))))
          (else (sumOdds (cdr L))))))

countAbove

Write countAbove, which returns how many numbers in L are strictly greater than X.

(countAbove 3 '(1 5 3 8))   ⇒ 2
(countAbove 0 '())          ⇒ 0
(countAbove 10 '(1 2))      ⇒ 0
(countAbove -1 '(0 -1 -2))  ⇒ 1

Not allowed: foldr, foldl, apply, count or filter.

Show answer

Count with a condition: (> (car L) X). Strictly greater, so X itself doesn't count.

(define countAbove
  (lambda (X L)
    (cond ((null? L) 0)
          ((> (car L) X) (+ 1 (countAbove X (cdr L))))
          (else (countAbove X (cdr L))))))

keepPositives

Write keepPositives, which returns a list of just the numbers in L that are greater than 0, in their original order.

(keepPositives '(3 -1 0 5))  ⇒ (3 5)
(keepPositives '(-1 -2))     ⇒ ()
(keepPositives '())          ⇒ ()
(keepPositives '(1 2))       ⇒ (1 2)

Not allowed: foldr, foldl, apply, filter, remove or filter-not.

Show answer

A hand-written filter: keep the first element with cons if it's > 0, otherwise skip it.

(define keepPositives
  (lambda (L)
    (cond ((null? L) '())
          ((> (car L) 0) (cons (car L) (keepPositives (cdr L))))
          (else (keepPositives (cdr L))))))

digitCount

Write digitCount, which takes a whole number N ≥ 0 and returns how many digits it has. 0 has one digit.

(digitCount 4096)  ⇒ 4
(digitCount 7)     ⇒ 1
(digitCount 0)     ⇒ 1
(digitCount 10)    ⇒ 2

Not allowed: number->string, string-length, log or apply.

Show answer

Each quotient by 10 removes one digit. Numbers under 10, including 0, have exactly one digit, and that's the base case.

(define digitCount
  (lambda (N)
    (cond ((< N 10) 1)                   ; one digit (this covers 0 too)
          (else (+ 1 (digitCount (quotient N 10)))))))

multiplyAll

Write multiplyAll, which returns a new list where every number in L is multiplied by N.

(multiplyAll 3 '(1 2 3))  ⇒ (3 6 9)
(multiplyAll 10 '())      ⇒ ()
(multiplyAll 0 '(4 5))    ⇒ (0 0)
(multiplyAll -1 '(2 -2))  ⇒ (-2 2)

Not allowed: foldr, foldl, apply or map.

Show answer

Pass N along unchanged in every recursive call, and cons (N × first) onto the rest.

(define multiplyAll
  (lambda (N L)
    (cond ((null? L) '())
          (else (cons (* N (car L)) (multiplyAll N (cdr L)))))))

Easy to mid

replaceAll

Write replaceAll, which returns L with every Old replaced by New.

(replaceAll 'a 'z '(a b a))  ⇒ (z b z)
(replaceAll 1 0 '(1 2 1 3))  ⇒ (0 2 0 3)
(replaceAll 'q 'r '())       ⇒ ()
(replaceAll 'x 'y '(a b))    ⇒ (a b)

Not allowed: map or foldr.

Show answer

Build a new list. If the first element equals Old, put New in its place, otherwise keep it. Either way, carry on with the rest.

(define replaceAll
  (lambda (Old New L)
    (cond ((null? L) '())
          ((equal? (car L) Old) (cons New (replaceAll Old New (cdr L))))
          (else (cons (car L) (replaceAll Old New (cdr L)))))))

myAppend

Write myAppend, which joins two lists: all of A, followed by all of B. The built-in append is off-limits.

(myAppend '(1 2) '(3 4))  ⇒ (1 2 3 4)
(myAppend '() '(a))       ⇒ (a)
(myAppend '(a) '())       ⇒ (a)
(myAppend '(x y z) '(w))  ⇒ (x y z w)

Not allowed: append, reverse, append* or foldr.

Show answer

Only A gets taken apart. When A runs out, the answer is simply B. Otherwise cons A's first element onto (rest of A appended to B).

(define myAppend
  (lambda (A B)
    (cond ((null? A) B)
          (else (cons (car A) (myAppend (cdr A) B))))))

addPairs

A and B are lists of numbers with the same length. Write addPairs, which returns a list of their element-by-element sums.

(addPairs '(1 2 3) '(10 20 30))  ⇒ (11 22 33)
(addPairs '() '())               ⇒ ()
(addPairs '(5) '(-5))            ⇒ (0)
(addPairs '(1 1) '(2 3))         ⇒ (3 4)

Not allowed: map or foldr.

Show answer

Walk both lists together, taking car and cdr of each in step. They're the same length, so checking one for empty is enough.

(define addPairs
  (lambda (A B)
    (cond ((null? A) '())
          (else (cons (+ (car A) (car B))
                      (addPairs (cdr A) (cdr B)))))))

everyOther

Write everyOther, which keeps the elements at positions 0, 2, 4, … of L and drops the rest.

(everyOther '(a b c d e))  ⇒ (a c e)
(everyOther '(1 2 3 4))    ⇒ (1 3)
(everyOther '())           ⇒ ()
(everyOther '(z))          ⇒ (z)
Show answer

Keep the first element, then skip the next one by recursing on cddr. A one-element list must be handled separately, because cddr of it would fail.

(define everyOther
  (lambda (L)
    (cond ((null? L) '())
          ((null? (cdr L)) L)                       ; one element left: keep it
          (else (cons (car L) (everyOther (cddr L)))))))   ; skip the next one

insertAfter

Write insertAfter, which returns L with Y inserted right after every occurrence of X.

(insertAfter 'a 'z '(a b a))  ⇒ (a z b a z)
(insertAfter 1 0 '(2 3))      ⇒ (2 3)
(insertAfter 'q 'r '())       ⇒ ()
(insertAfter 'b 'b '(b c))    ⇒ (b b c)

Not allowed: append-map or foldr.

Show answer

When you find X, output X, then Y, then recurse on the rest of the ORIGINAL list. Don't recurse on the list with Y in it, or Y = X would loop forever.

(define insertAfter
  (lambda (X Y L)
    (cond ((null? L) '())
          ((equal? (car L) X)
           (cons X (cons Y (insertAfter X Y (cdr L)))))   ; recurse past the inserted Y
          (else (cons (car L) (insertAfter X Y (cdr L)))))))

maxList

Write maxList, which returns the largest number in a non-empty list. The built-in max is off-limits.

(maxList '(3 9 2))     ⇒ 9
(maxList '(5))         ⇒ 5
(maxList '(-4 -1 -8))  ⇒ -1
(maxList '(7 7 2))     ⇒ 7

Not allowed: max, apply, sort, argmax, argmin, foldl or foldr.

Show answer

A one-element list is its own maximum. Otherwise compare the first element with the max of the rest; let stops you computing that max twice.

(define maxList
  (lambda (L)
    (cond ((null? (cdr L)) (car L))
          (else (let ((restMax (maxList (cdr L))))
                  (if (> (car L) restMax) (car L) restMax))))))

countNumbers

L is a flat list that can contain numbers, symbols and lists. Write countNumbers, which returns how many of its elements are numbers. Don't look inside nested lists.

(countNumbers '(1 a 2 b c 3))  ⇒ 3
(countNumbers '(a b))          ⇒ 0
(countNumbers '())             ⇒ 0
(countNumbers '(4 (1 2) x 5))  ⇒ 2

Not allowed: count, filter, filter-not, foldl or foldr.

Show answer

Count with a condition using number?. A nested list isn't a number, so it's skipped without looking inside.

(define countNumbers
  (lambda (L)
    (cond ((null? L) 0)
          ((number? (car L)) (+ 1 (countNumbers (cdr L))))
          (else (countNumbers (cdr L))))))

makeRange

Write makeRange, which takes whole numbers A ≤ B and returns the list (A A+1 … B-1). B itself is not included, so when A = B the answer is empty.

(makeRange 2 6)   ⇒ (2 3 4 5)
(makeRange 0 1)   ⇒ (0)
(makeRange 4 4)   ⇒ ()
(makeRange -2 1)  ⇒ (-2 -1 0)

Not allowed: range, build-list or inclusive-range.

Show answer

Recursion that counts UP: when A reaches B, stop with '(). Otherwise cons A onto the range from A+1.

(define makeRange
  (lambda (A B)
    (cond ((= A B) '())
          (else (cons A (makeRange (+ A 1) B))))))

stutter

Write stutter, which repeats every element of L twice in a row.

(stutter '(a b c))  ⇒ (a a b b c c)
(stutter '())       ⇒ ()
(stutter '(1))      ⇒ (1 1)
(stutter '((x) y))  ⇒ ((x) (x) y y)

Not allowed: append-map, foldr or map.

Show answer

cons the first element on TWICE, then stutter the rest.

(define stutter
  (lambda (L)
    (cond ((null? L) '())
          (else (cons (car L) (cons (car L) (stutter (cdr L))))))))

indexOf

Write indexOf, which returns the position (counting from 0) of the first X in L, or -1 if X isn't there.

(indexOf 'c '(a b c d))  ⇒ 2
(indexOf 'a '(a b a))    ⇒ 0
(indexOf 'z '(a b))      ⇒ -1
(indexOf 1 '())          ⇒ -1
(indexOf 'd '(a b c d))  ⇒ 3

Not allowed: index-of, indexes-of, member or memf.

Show answer

Base cases: empty gives −1, a match at the front gives 0. Otherwise find the position in the rest and add 1, but only if it wasn't −1. Adding 1 to "not found" would give a wrong 0.

(define indexOf
  (lambda (X L)
    (cond ((null? L) -1)
          ((equal? X (car L)) 0)
          (else (let ((i (indexOf X (cdr L))))
                  (if (= i -1) -1 (+ i 1)))))))   ; don't add 1 to "not found"

listEqual

Write listEqual, which returns #t if the number lists A and B have the same elements in the same order, and #f otherwise. equal? is off-limits; compare numbers with =.

(listEqual '(1 2 3) '(1 2 3))  ⇒ #t
(listEqual '(1 2) '(1 2 3))    ⇒ #f
(listEqual '() '())            ⇒ #t
(listEqual '(1 2 3) '(1 9 3))  ⇒ #f
(listEqual '(4) '())           ⇒ #f

Not allowed: foldr, foldl, apply, equal?, eqv? or eq?.

Show answer

Both empty: equal. Exactly one empty: they're different lengths. Otherwise the first numbers must be = and the rests must match too.

(define listEqual
  (lambda (A B)
    (cond ((and (null? A) (null? B)) #t)
          ((or (null? A) (null? B)) #f)          ; one ran out first
          ((= (car A) (car B)) (listEqual (cdr A) (cdr B)))
          (else #f))))

isPrefix

Write isPrefix, which returns #t if A is a prefix of B: B starts with exactly the elements of A, in order.

(isPrefix '(a b) '(a b c))  ⇒ #t
(isPrefix '() '(x y))       ⇒ #t
(isPrefix '(a c) '(a b c))  ⇒ #f
(isPrefix '(a b c) '(a b))  ⇒ #f
(isPrefix '(1) '(1))        ⇒ #t

Not allowed: foldr, foldl, apply, take, list-prefix? or string-prefix?.

Show answer

An empty A is a prefix of anything. If B runs out first, the answer is #f. Otherwise the fronts must match and you recurse on both rests.

(define isPrefix
  (lambda (A B)
    (cond ((null? A) #t)
          ((null? B) #f)
          ((equal? (car A) (car B)) (isPrefix (cdr A) (cdr B)))
          (else #f))))

takeN

Write takeN, which returns the first N elements of L. If L has fewer than N elements, return all of it.

(takeN 2 '(a b c d))  ⇒ (a b)
(takeN 0 '(a b))      ⇒ ()
(takeN 5 '(1 2))      ⇒ (1 2)
(takeN 3 '())         ⇒ ()

Not allowed: foldr, foldl, apply, take, list-head, drop or list-tail.

Show answer

Stop when you've taken N or the list runs out. Each step conses one element and lowers N.

(define takeN
  (lambda (N L)
    (cond ((or (= N 0) (null? L)) '())
          (else (cons (car L) (takeN (- N 1) (cdr L)))))))

dropN

Write dropN, which returns L without its first N elements. If L has fewer than N elements, return '().

(dropN 2 '(a b c d))  ⇒ (c d)
(dropN 0 '(a b))      ⇒ (a b)
(dropN 5 '(1 2))      ⇒ ()
(dropN 1 '(x))        ⇒ ()

Not allowed: foldr, foldl, apply, drop, list-tail, take or list-ref.

Show answer

Stop when N is 0 and return what's left. If the list runs out first, return '().

(define dropN
  (lambda (N L)
    (cond ((= N 0) L)
          ((null? L) '())
          (else (dropN (- N 1) (cdr L))))))

lastIndexOf

Write lastIndexOf, which returns the position (starting at 0) of the last occurrence of X in L, or -1 if it isn't there.

(lastIndexOf 'a '(a b a c))  ⇒ 2
(lastIndexOf 'b '(a b c))    ⇒ 1
(lastIndexOf 'z '(a b))      ⇒ -1
(lastIndexOf 'a '())         ⇒ -1
(lastIndexOf 'x '(x))        ⇒ 0

Not allowed: foldr, foldl, apply, index-of, indexes-of, list-index or reverse.

Show answer

Look in the REST first: a later match beats this one. If the rest found something, add 1 for this position. Only if it found nothing does the front element matter.

(define lastIndexOf
  (lambda (X L)
    (cond ((null? L) -1)
          (else (let ((later (lastIndexOf X (cdr L))))   ; a later match wins
                  (cond ((not (= later -1)) (+ later 1))
                        ((equal? X (car L)) 0)
                        (else -1)))))))

mergeSorted

Write mergeSorted, which takes two lists of numbers, each sorted from smallest to largest, and returns one sorted list containing all the elements of both.

(mergeSorted '(1 4 6) '(2 3 7))  ⇒ (1 2 3 4 6 7)
(mergeSorted '() '(1 2))         ⇒ (1 2)
(mergeSorted '(5) '())           ⇒ (5)
(mergeSorted '(1 2 2) '(2 3))    ⇒ (1 2 2 2 3)

Not allowed: foldr, foldl, apply, sort, merge or append.

Show answer

Two base cases: if either list is empty, return the other. Otherwise take the smaller front element and merge what remains. <= takes from A on ties.

(define mergeSorted
  (lambda (A B)
    (cond ((null? A) B)
          ((null? B) A)
          ((<= (car A) (car B)) (cons (car A) (mergeSorted (cdr A) B)))
          (else (cons (car B) (mergeSorted A (cdr B)))))))

compress

Write compress, which collapses every run of consecutive equal elements in L into a single copy.

(compress '(a a b c c c a))  ⇒ (a b c a)
(compress '())               ⇒ ()
(compress '(x))              ⇒ (x)
(compress '(1 1 1))          ⇒ (1)

Not allowed: foldr, foldl, apply, remove-duplicates or group-by.

Show answer

Compare each element with the next one. If they're equal, drop the first and keep going, so the LAST copy of each run survives.

(define compress
  (lambda (L)
    (cond ((or (null? L) (null? (cdr L))) L)
          ((equal? (car L) (cadr L)) (compress (cdr L)))     ; same as the next: drop it
          (else (cons (car L) (compress (cdr L)))))))

dotProduct

Write dotProduct, which takes two number lists of the same length and returns the sum of the products of matching elements: a₁b₁ + a₂b₂ + ….

(dotProduct '(1 2 3) '(4 5 6))  ⇒ 32
(dotProduct '() '())            ⇒ 0
(dotProduct '(2) '(-3))         ⇒ -6
(dotProduct '(1 0 1) '(5 9 5))  ⇒ 10

Not allowed: foldr, foldl, apply or map.

Show answer

Walk both lists together, adding the product of the two fronts. Empty lists give 0.

(define dotProduct
  (lambda (A B)
    (cond ((null? A) 0)
          (else (+ (* (car A) (car B))
                   (dotProduct (cdr A) (cdr B)))))))

countMatches

Write countMatches, which returns how many positions hold the same element in A and B. Stop when either list runs out.

(countMatches '(a b c) '(a x c))  ⇒ 2
(countMatches '(1 2) '(1 2 3 4))  ⇒ 2
(countMatches '() '(a))           ⇒ 0
(countMatches '(a b) '(b a))      ⇒ 0

Not allowed: foldr, foldl, apply, count or map.

Show answer

Walk both lists in step and stop when EITHER runs out. Add 1 when the fronts are equal?.

(define countMatches
  (lambda (A B)
    (cond ((or (null? A) (null? B)) 0)
          ((equal? (car A) (car B)) (+ 1 (countMatches (cdr A) (cdr B))))
          (else (countMatches (cdr A) (cdr B))))))

rotateLeft

Write rotateLeft, which moves the first element of L to the end. An empty list stays empty.

(rotateLeft '(a b c))    ⇒ (b c a)
(rotateLeft '(x))        ⇒ (x)
(rotateLeft '())         ⇒ ()
(rotateLeft '((1 2) 3))  ⇒ (3 (1 2))

Not allowed: reverse, last or rotate.

Show answer

Move the first element to the end: (append (cdr L) (list (car L))). It has to be wrapped in a list, because append joins lists.

(define rotateLeft
  (lambda (L)
    (cond ((null? L) '())
          (else (append (cdr L) (list (car L)))))))

elementAfter

Write elementAfter, which returns the element right after the first X in L. If X isn't there, or is the last element, return #f.

(elementAfter 'b '(a b c d))  ⇒ c
(elementAfter 'd '(a b c d))  ⇒ #f
(elementAfter 'z '(a b))      ⇒ #f
(elementAfter 'a '(a a b))    ⇒ a
(elementAfter 'a '())         ⇒ #f

Not allowed: foldr, foldl, apply, member, memq, memv or index-of.

Show answer

Find X. If it's the last element there is nothing after it, so return #f. Otherwise return the next one, (cadr L).

(define elementAfter
  (lambda (X L)
    (cond ((null? L) #f)
          ((equal? X (car L))
           (if (null? (cdr L)) #f (cadr L)))    ; X is last: nothing after it
          (else (elementAfter X (cdr L))))))

countRuns

Write countRuns, which returns how many runs of consecutive equal elements there are in L.

(countRuns '(a a b c c a))  ⇒ 4
(countRuns '())             ⇒ 0
(countRuns '(x))            ⇒ 1
(countRuns '(1 1 1))        ⇒ 1
(countRuns '(1 2 1 2))      ⇒ 4

Not allowed: foldr, foldl, apply, group-by, remove-duplicates or length.

Show answer

A run ends wherever an element differs from the next one. Count those boundaries, and the final element always ends a run.

(define countRuns
  (lambda (L)
    (cond ((null? L) 0)
          ((null? (cdr L)) 1)
          ((equal? (car L) (cadr L)) (countRuns (cdr L)))   ; same run continues
          (else (+ 1 (countRuns (cdr L)))))))               ; a run ends here

isSorted

Write isSorted, which returns #t if the numbers in L never go down (each is ≤ the next), and #f otherwise.

(isSorted '(1 2 2 5))  ⇒ #t
(isSorted '(1 3 2))    ⇒ #f
(isSorted '())         ⇒ #t
(isSorted '(7))        ⇒ #t
(isSorted '(5 4))      ⇒ #f

Not allowed: foldr, foldl, apply, sort or sorted?.

Show answer

Check each neighbouring pair with <=. Lists of length 0 or 1 are sorted automatically.

(define isSorted
  (lambda (L)
    (cond ((or (null? L) (null? (cdr L))) #t)
          ((<= (car L) (cadr L)) (isSorted (cdr L)))
          (else #f))))

insertSorted

L is sorted from smallest to largest. Write insertSorted, which returns a new sorted list with the number X added in the right place.

(insertSorted 3 '(1 2 4 5))  ⇒ (1 2 3 4 5)
(insertSorted 0 '(1 2))      ⇒ (0 1 2)
(insertSorted 9 '(1 2))      ⇒ (1 2 9)
(insertSorted 5 '())         ⇒ (5)
(insertSorted 2 '(1 2 3))    ⇒ (1 2 2 3)

Not allowed: foldr, foldl, apply, sort or append.

Show answer

Walk until X fits before the current element. Then cons X there and keep the rest unchanged. An empty list just becomes (X).

(define insertSorted
  (lambda (X L)
    (cond ((null? L) (list X))
          ((<= X (car L)) (cons X L))
          (else (cons (car L) (insertSorted X (cdr L)))))))

firstDifference

Write firstDifference, which returns the first position (starting at 0) where A and B differ. If one list runs out before the other, that position counts as a difference. If they're identical, return -1.

(firstDifference '(a b c) '(a x c))  ⇒ 1
(firstDifference '(1 2) '(1 2))      ⇒ -1
(firstDifference '(1 2) '(1 2 3))    ⇒ 2
(firstDifference '() '(a))           ⇒ 0
(firstDifference '() '())            ⇒ -1

Not allowed: foldr, foldl or apply.

Show answer

Same −1 trick as indexOf. Both empty: −1 (identical). One empty, or the fronts differ: 0. Otherwise recurse and add 1 unless it's −1.

(define firstDifference
  (lambda (A B)
    (cond ((and (null? A) (null? B)) -1)
          ((or (null? A) (null? B)) 0)
          ((not (equal? (car A) (car B))) 0)
          (else (let ((d (firstDifference (cdr A) (cdr B))))
                  (if (= d -1) -1 (+ d 1)))))))

replaceNth

Write replaceNth, which returns L with the element at position N (starting at 0) replaced by X. If N is past the end, return L unchanged.

(replaceNth 1 'z '(a b c))  ⇒ (a z c)
(replaceNth 0 'z '(a b))    ⇒ (z b)
(replaceNth 5 'z '(a b))    ⇒ (a b)
(replaceNth 0 'z '())       ⇒ ()

Not allowed: foldr, foldl, apply, list-set, list-update or list-ref.

Show answer

Count N down while copying elements. At 0, swap in X and keep the rest. If the list runs out first, nothing changes.

(define replaceNth
  (lambda (N X L)
    (cond ((null? L) '())
          ((= N 0) (cons X (cdr L)))
          (else (cons (car L) (replaceNth (- N 1) X (cdr L)))))))

removeNth

Write removeNth, which returns L without the element at position N (starting at 0). If N is past the end, return L unchanged.

(removeNth 1 '(a b c))    ⇒ (a c)
(removeNth 0 '(a))        ⇒ ()
(removeNth 4 '(a b))      ⇒ (a b)
(removeNth 2 '(1 2 3 4))  ⇒ (1 2 4)

Not allowed: foldr, foldl, apply, list-ref, drop, take or remove.

Show answer

Like replaceNth, but at position 0 you return (cdr L), dropping that one element.

(define removeNth
  (lambda (N L)
    (cond ((null? L) '())
          ((= N 0) (cdr L))
          (else (cons (car L) (removeNth (- N 1) (cdr L)))))))

sumUntilZero

Write sumUntilZero, which adds up the numbers in L from the start, stopping at the first 0 (the 0 and everything after it are ignored).

(sumUntilZero '(3 4 0 10))  ⇒ 7
(sumUntilZero '(1 2))       ⇒ 3
(sumUntilZero '(0 5))       ⇒ 0
(sumUntilZero '())          ⇒ 0

Not allowed: foldr, foldl, apply, takef or take-while.

Show answer

A 0 acts like the end of the list: it returns 0 and stops the recursion, so nothing after it is added.

(define sumUntilZero
  (lambda (L)
    (cond ((null? L) 0)
          ((= (car L) 0) 0)              ; stop here
          (else (+ (car L) (sumUntilZero (cdr L)))))))

pairwiseMax

Write pairwiseMax, which returns a list of the larger of each pair of matching elements in A and B. Stop when the shorter list runs out.

(pairwiseMax '(1 5 3) '(4 2 3))  ⇒ (4 5 3)
(pairwiseMax '(1 2 3) '(0))      ⇒ (1)
(pairwiseMax '() '(1))           ⇒ ()
(pairwiseMax '(-1 -2) '(-3 -4))  ⇒ (-1 -2)

Not allowed: foldr, foldl, apply or map.

Show answer

Walk both lists in step and stop at the shorter. cons the larger of the two fronts.

(define pairwiseMax
  (lambda (A B)
    (cond ((or (null? A) (null? B)) '())
          (else (cons (if (> (car A) (car B)) (car A) (car B))
                      (pairwiseMax (cdr A) (cdr B)))))))

compareLengths

Write compareLengths, which returns the symbol shorter if A has fewer elements than B, longer if it has more, and same if they're equal. length is off-limits: walk both lists together.

(compareLengths '(a b) '(1 2 3))  ⇒ shorter
(compareLengths '(a b c) '(1))    ⇒ longer
(compareLengths '(a) '(b))        ⇒ same
(compareLengths '() '())          ⇒ same
(compareLengths '() '(x))         ⇒ shorter

Not allowed: foldr, foldl, apply or length.

Show answer

Walk both lists together. Whichever runs out first is shorter. If they run out together, they're the same length.

(define compareLengths
  (lambda (A B)
    (cond ((and (null? A) (null? B)) 'same)
          ((null? A) 'shorter)
          ((null? B) 'longer)
          (else (compareLengths (cdr A) (cdr B))))))

countConsecutive

Write countConsecutive, which counts how many times an element of L is immediately followed by the same element.

(countConsecutive '(a b b c d d c c))    ⇒ 3
(countConsecutive '(a b b b c d d c c))  ⇒ 4
(countConsecutive '(a a a a a a b))      ⇒ 5
(countConsecutive '())                   ⇒ 0
(countConsecutive '(x))                  ⇒ 0
Show answer

Compare each element with the next and add 1 when they're equal. Overlapping pairs count separately, so b b b gives 2.

(define countConsecutive
  (lambda (L)
    (cond ((or (null? L) (null? (cdr L))) 0)
          ((equal? (car L) (cadr L)) (+ 1 (countConsecutive (cdr L))))
          (else (countConsecutive (cdr L))))))

Mid

revAcc

Write revAcc, which reverses a list. Both reverse and append are off-limits, so you need a helper that carries the answer-so-far as an extra argument.

(revAcc '(1 2 3))    ⇒ (3 2 1)
(revAcc '())         ⇒ ()
(revAcc '(a))        ⇒ (a)
(revAcc '((1 2) 3))  ⇒ (3 (1 2))

Not allowed: reverse, append, foldl or foldr.

Show answer

The accumulator trick: carry the reversed-so-far list as an extra argument. Each step moves the front element onto the front of the accumulator, which naturally reverses the order.

(define revHelp                          ; acc = what's been reversed so far
  (lambda (L acc)
    (cond ((null? L) acc)
          (else (revHelp (cdr L) (cons (car L) acc))))))

(define revAcc
  (lambda (L)
    (revHelp L '())))

digitsToNumber

L is a list of digits. Write digitsToNumber, which turns it into the number those digits spell. The empty list gives 0.

(digitsToNumber '(3 2 7))  ⇒ 327
(digitsToNumber '(5))      ⇒ 5
(digitsToNumber '(1 0 0))  ⇒ 100
(digitsToNumber '())       ⇒ 0
(digitsToNumber '(0 4))    ⇒ 4

Not allowed: apply, foldl, foldr or string->number.

Show answer

Accumulator: start at 0, and for each digit multiply what you have by 10 and add the digit. (3 2 7) gives 3, then 32, then 327.

(define toNum                            ; acc = number built so far
  (lambda (L acc)
    (cond ((null? L) acc)
          (else (toNum (cdr L) (+ (* 10 acc) (car L)))))))

(define digitsToNumber
  (lambda (L)
    (toNum L 0)))

deepCount

Write deepCount, which counts how many times the symbol or number X appears anywhere in L, at any depth of nesting.

(deepCount 'a '(a (b a) ((a)) c))  ⇒ 3
(deepCount 1 '(1 2 3))             ⇒ 1
(deepCount 'z '((x) (y)))          ⇒ 0
(deepCount 'a '())                 ⇒ 0
(deepCount 'b '(((b b)) b))        ⇒ 3

Not allowed: flatten or count.

Show answer

The four-case "deep" shape. Empty: 0. If the first element is a list, count inside it AND in the rest. If it matches, add 1. Otherwise move on.

(define deepCount
  (lambda (X L)
    (cond ((null? L) 0)
          ((list? (car L)) (+ (deepCount X (car L)) (deepCount X (cdr L))))
          ((equal? X (car L)) (+ 1 (deepCount X (cdr L))))
          (else (deepCount X (cdr L))))))

maxDepth

Write maxDepth, which measures how deeply a list is nested:

  • something that isn't a list (a number or symbol) has depth 0
  • the empty list has depth 1
  • any other list is 1 deeper than its deepest element.
(maxDepth '(1 2 3))          ⇒ 1
(maxDepth '(1 (2 (3))))      ⇒ 3
(maxDepth '())               ⇒ 1
(maxDepth '((())))           ⇒ 3
(maxDepth '(a (b) ((c)) d))  ⇒ 3
(maxDepth 'x)                ⇒ 0

Not allowed: flatten.

Show answer

Non-lists have depth 0 and the empty list has depth 1. Any other list is 1 deeper than its deepest element, and map with apply max finds that.

(define maxDepth
  (lambda (L)
    (cond ((not (list? L)) 0)
          ((null? L) 1)
          (else (+ 1 (apply max (map maxDepth L)))))))

longestRun

Write longestRun, which returns the length of the longest run of equal elements that sit next to each other in L. The empty list gives 0.

(longestRun '(a a b b b c))  ⇒ 3
(longestRun '(1 2 3))        ⇒ 1
(longestRun '())             ⇒ 0
(longestRun '(x x x))        ⇒ 3
(longestRun '(1 1 2 1 1 1))  ⇒ 3
Show answer

Measure the run at the front, skip past it, and take the bigger of that run and the longest run in the rest. Two small helpers keep this readable.

(define runLength                        ; length of the run at the front
  (lambda (L)
    (cond ((null? (cdr L)) 1)
          ((equal? (car L) (cadr L)) (+ 1 (runLength (cdr L))))
          (else 1))))

(define afterRun                         ; what's left after the front run
  (lambda (L)
    (cond ((null? (cdr L)) '())
          ((equal? (car L) (cadr L)) (afterRun (cdr L)))
          (else (cdr L)))))

(define longestRun
  (lambda (L)
    (cond ((null? L) 0)
          (else (max (runLength L) (longestRun (afterRun L)))))))

interleave

Write interleave, which alternates elements from A and B, starting with A. When one list runs out, the rest of the other list follows.

(interleave '(1 2 3) '(a b c))  ⇒ (1 a 2 b 3 c)
(interleave '(1 2) '(a b c d))  ⇒ (1 a 2 b c d)
(interleave '(x) '())           ⇒ (x)
(interleave '() '(y z))         ⇒ (y z)
Show answer

Take A's first element, then swap the roles of the lists: (interleave B (cdr A)). When A runs out, whatever's left of B follows.

(define interleave
  (lambda (A B)
    (cond ((null? A) B)
          (else (cons (car A) (interleave B (cdr A)))))))   ; swap the lists each time

dedup

Write dedup, which removes duplicates from L, keeping only the last occurrence of each element. Elements can be lists, so compare with equal?. The built-in member is off-limits.

(dedup '(a b a c b))  ⇒ (a c b)
(dedup '(1 2 3))      ⇒ (1 2 3)
(dedup '())           ⇒ ()
(dedup '(x x x))      ⇒ (x)
(dedup '((1) 2 (1)))  ⇒ (2 (1))

Not allowed: member, memq, remove-duplicates, memv or memf.

Show answer

To keep the LAST copy, drop an element whenever another copy appears later in the list. Membership is checked with a hand-written isIn, because member is banned.

(define isIn
  (lambda (X L)
    (cond ((null? L) #f)
          ((equal? X (car L)) #t)
          (else (isIn X (cdr L))))))

(define dedup
  (lambda (L)
    (cond ((null? L) '())
          ((isIn (car L) (cdr L)) (dedup (cdr L)))   ; a later copy exists: drop this one
          (else (cons (car L) (dedup (cdr L)))))))

splitEvenOdd

Write splitEvenOdd, which returns a list of two lists: the even numbers of L, then the odd numbers, each in their original order.

(splitEvenOdd '(1 2 3 4 5))  ⇒ ((2 4) (1 3 5))
(splitEvenOdd '())           ⇒ (() ())
(splitEvenOdd '(2 4))        ⇒ ((2 4) ())
(splitEvenOdd '(7))          ⇒ (() (7))

Not allowed: filter, filter-not or foldr.

Show answer

The recursion returns TWO lists. Get them for the rest, then add the first element to whichever list it belongs in. The base case is (() ()).

(define splitEvenOdd
  (lambda (L)
    (cond ((null? L) (list '() '()))
          (else (let ((r (splitEvenOdd (cdr L))))   ; (evens odds) for the rest
                  (if (even? (car L))
                      (list (cons (car L) (car r)) (cadr r))
                      (list (car r) (cons (car L) (cadr r)))))))))

zip

Write zip, which pairs up elements of A and B by position, as 2-element lists. Stop when the shorter list runs out.

(zip '(a b c) '(1 2 3))  ⇒ ((a 1) (b 2) (c 3))
(zip '(x y) '(1))        ⇒ ((x 1))
(zip '() '(1 2))         ⇒ ()
(zip '(p) '((1 2)))      ⇒ ((p (1 2)))

Not allowed: map or foldr.

Show answer

Walk both lists in step and stop at the shorter. Each step conses a two-element list of the fronts.

(define zip
  (lambda (A B)
    (cond ((or (null? A) (null? B)) '())
          (else (cons (list (car A) (car B)) (zip (cdr A) (cdr B)))))))

lookup

AL is an association list: a list of 2-element lists (key value). Write lookup, which returns the value paired with the first key equal to K, or #f if there's none.

(lookup 'b '((a 1) (b 2) (c 3)))  ⇒ 2
(lookup 'z '((a 1)))              ⇒ #f
(lookup 'a '())                   ⇒ #f
(lookup 'x '((x (1 2)) (x 5)))    ⇒ (1 2)
(lookup 3 '((1 one) (3 three)))   ⇒ three

Not allowed: assoc, assq, assv, assf or findf.

Show answer

Each entry is (key value). Compare (car (car AL)) with K, and on a match return (cadr (car AL)). If the table runs out, return #f.

(define lookup
  (lambda (K AL)
    (cond ((null? AL) #f)
          ((equal? K (car (car AL))) (cadr (car AL)))
          (else (lookup K (cdr AL))))))

alternateSum

Write alternateSum, which takes a list of numbers and returns the first minus the second, plus the third, minus the fourth, and so on. The empty list gives 0.

So (alternateSum '(5 3 8)) is 5 − 3 + 8 = 10.

(alternateSum '(1 2 3 4))    ⇒ -2
(alternateSum '(10))         ⇒ 10
(alternateSum '())           ⇒ 0
(alternateSum '(5 3 8))      ⇒ 10
(alternateSum '(1 1 1 1 1))  ⇒ 1
Show answer

a − (b − (c − …)) flips the sign each step, so a − b + c − d … falls out of a single recursion with no flag.

;; a - (b - (c - ...)) flips the sign each step: a - b + c - ...
(define alternateSum
  (lambda (L)
    (cond ((null? L) 0)
          (else (- (car L) (alternateSum (cdr L)))))))

pairUp

Write pairUp, which groups L into 2-element lists, taking the elements two at a time from the front. If there's an element left over at the end, it goes into a list on its own.

(pairUp '(1 2 3 4))      ⇒ ((1 2) (3 4))
(pairUp '(a b c))        ⇒ ((a b) (c))
(pairUp '())             ⇒ ()
(pairUp '(x))            ⇒ ((x))
(pairUp '((1) 2 3 (4)))  ⇒ (((1) 2) (3 (4)))
Show answer

Take two elements at a time with cddr. A single leftover element becomes a list of its own.

(define pairUp
  (lambda (L)
    (cond ((null? L) '())
          ((null? (cdr L)) (list L))     ; one left over
          (else (cons (list (car L) (cadr L)) (pairUp (cddr L)))))))

cumulative

Write cumulative, which returns the running totals of a list of numbers: each element of the answer is the sum of everything up to and including that position.

(cumulative '(1 2 3 4))  ⇒ (1 3 6 10)
(cumulative '(5))        ⇒ (5)
(cumulative '())         ⇒ ()
(cumulative '(3 -3 3))   ⇒ (3 0 3)
(cumulative '(0 0 7))    ⇒ (0 0 7)
Show answer

Carry the running total as an extra argument. Each step adds the next number, outputs the new total, and passes it on.

(define runningFrom                      ; total = sum of everything before L
  (lambda (L total)
    (cond ((null? L) '())
          (else (let ((t (+ total (car L))))
                  (cons t (runningFrom (cdr L) t)))))))

(define cumulative
  (lambda (L)
    (runningFrom L 0)))

listDiff

Write listDiff, which returns the elements of A that do not appear anywhere in B, in their original order. Elements can be lists, so compare with equal?.

(listDiff '(1 2 3 4) '(2 4))    ⇒ (1 3)
(listDiff '(a b a c) '(a))      ⇒ (b c)
(listDiff '() '(1))             ⇒ ()
(listDiff '(x y) '())           ⇒ (x y)
(listDiff '((1 2) 3) '((1 2)))  ⇒ (3)

Not allowed: member, memq, memv, remove*, filter, filter-not or remove.

Show answer

Keep an element of A only if it's not anywhere in B. Membership uses a hand-written isIn with equal?.

(define isIn
  (lambda (X L)
    (cond ((null? L) #f)
          ((equal? X (car L)) #t)
          (else (isIn X (cdr L))))))

(define listDiff
  (lambda (A B)
    (cond ((null? A) '())
          ((isIn (car A) B) (listDiff (cdr A) B))
          (else (cons (car A) (listDiff (cdr A) B))))))

isPalindrome

Write isPalindrome, which returns #t if L reads the same forwards and backwards, and #f otherwise. The built-in reverse is off-limits.

(isPalindrome '(r a c e c a r))  ⇒ #t
(isPalindrome '(1 2 3))          ⇒ #f
(isPalindrome '())               ⇒ #t
(isPalindrome '(x))              ⇒ #t
(isPalindrome '(1 2 2 1))        ⇒ #t
(isPalindrome '((1 2) 3 (1 2)))  ⇒ #t

Not allowed: reverse or foldl.

Show answer

Reverse the list with an accumulator helper (reverse is banned) and compare with equal?.

(define revHelp
  (lambda (L acc)
    (cond ((null? L) acc)
          (else (revHelp (cdr L) (cons (car L) acc))))))

(define isPalindrome
  (lambda (L)
    (equal? L (revHelp L '()))))

splitAt

Write splitAt, which returns a list of two lists: the first N elements of L, then everything after them. If L has fewer than N elements, they all go in the first list.

(splitAt 2 '(a b c d))  ⇒ ((a b) (c d))
(splitAt 0 '(1 2))      ⇒ (() (1 2))
(splitAt 5 '(1 2))      ⇒ ((1 2) ())
(splitAt 1 '())         ⇒ (() ())
(splitAt 3 '(x y z))    ⇒ ((x y z) ())

Not allowed: take, drop, list-tail, take-right, drop-right or split-at.

Show answer

The recursion returns two lists. When N hits 0 (or L is empty), everything left goes in the second list. Otherwise put (car L) onto the front of the first list.

(define splitAt
  (lambda (N L)
    (cond ((or (= N 0) (null? L)) (list '() L))
          (else (let ((r (splitAt (- N 1) (cdr L))))
                  (list (cons (car L) (car r)) (cadr r)))))))

minMax

L is a non-empty list of numbers. Write minMax, which returns a 2-element list: the smallest number in L, then the biggest. Do it in one recursion, not two.

(minMax '(3 9 1 4))    ⇒ (1 9)
(minMax '(7))          ⇒ (7 7)
(minMax '(5 5 5))      ⇒ (5 5)
(minMax '(-2 10 -8))   ⇒ (-8 10)
(minMax '(1 2 3 4 5))  ⇒ (1 5)

Not allowed: argmin, argmax, sort or apply.

Show answer

One pass that returns a pair. Get (min max) for the rest, then compare the first element against both. A one-element list is its own min and max.

(define minMax
  (lambda (L)
    (cond ((null? (cdr L)) (list (car L) (car L)))
          (else (let ((r (minMax (cdr L))))     ; (min max) of the rest
                  (list (min (car L) (car r))
                        (max (car L) (cadr r))))))))

flattenOnce

Write flattenOnce, which removes exactly one level of nesting: every element of L that is a list gets its contents spliced into the answer. Anything nested deeper stays nested.

(flattenOnce '((1 2) 3 (4 (5))))  ⇒ (1 2 3 4 (5))
(flattenOnce '(a b))              ⇒ (a b)
(flattenOnce '())                 ⇒ ()
(flattenOnce '(() (x) ()))        ⇒ (x)
(flattenOnce '(((a)) b))          ⇒ ((a) b)

Not allowed: flatten, append*, apply or append-map.

Show answer

When an element is a list, append its contents WITHOUT recursing into it. That removes exactly one level.

(define flattenOnce
  (lambda (L)
    (cond ((null? L) '())
          ((list? (car L)) (append (car L) (flattenOnce (cdr L))))   ; splice, don't recurse inside
          (else (cons (car L) (flattenOnce (cdr L)))))))

deepMax

L is a nested list of numbers. Every list in it, at every level, is non-empty. Write deepMax, which returns the biggest number anywhere in L.

(deepMax '(3 (8 2) ((5))))    ⇒ 8
(deepMax '(4))                ⇒ 4
(deepMax '((((1)))))          ⇒ 1
(deepMax '(1 (2 (3 (9))) 4))  ⇒ 9
(deepMax '((-5) (-2 -9)))     ⇒ -2

Not allowed: flatten, apply, argmax or sort.

Show answer

Each element is either a number or a list whose biggest number is its own deepMax. Take the max of the first element's value and the deepMax of the rest.

(define biggestIn                        ; a number, or the deepMax of a list
  (lambda (x)
    (if (list? x) (deepMax x) x)))

(define deepMax
  (lambda (L)
    (cond ((null? (cdr L)) (biggestIn (car L)))
          (else (max (biggestIn (car L)) (deepMax (cdr L)))))))

updateKey

AL is a list of (key value) pairs. Write updateKey, which returns a new list where the first pair with key K has its value replaced by V. If no key equals K, the pair (K V) is added at the end.

(updateKey 'b 9 '((a 1) (b 2) (c 3)))  ⇒ ((a 1) (b 9) (c 3))
(updateKey 'z 0 '((a 1)))              ⇒ ((a 1) (z 0))
(updateKey 'k 5 '())                   ⇒ ((k 5))
(updateKey 'a 7 '((a 1) (a 2)))        ⇒ ((a 7) (a 2))
(updateKey 'x '(1 2) '((x 0)))         ⇒ ((x (1 2)))

Not allowed: assoc, assq, assv or list-set.

Show answer

Copy pairs until the key matches, then replace that one pair and keep the rest untouched. If you reach the end, the base case adds (K V).

(define updateKey
  (lambda (K V AL)
    (cond ((null? AL) (list (list K V)))                ; not found: add at the end
          ((equal? K (car (car AL))) (cons (list K V) (cdr AL)))
          (else (cons (car AL) (updateKey K V (cdr AL)))))))

chunk

N is at least 1. Write chunk, which splits L into consecutive groups of N elements. The last group can be shorter if there aren't enough elements left.

(chunk 2 '(1 2 3 4 5))    ⇒ ((1 2) (3 4) (5))
(chunk 3 '(a b c d e f))  ⇒ ((a b c) (d e f))
(chunk 1 '(x y))          ⇒ ((x) (y))
(chunk 4 '(1 2))          ⇒ ((1 2))
(chunk 2 '())             ⇒ ()

Not allowed: take, drop, list-tail or split-at.

Show answer

Take the first N elements as one group, drop them, and chunk the rest. Hand-written take/drop helpers stop early if the list is short.

(define firstN
  (lambda (n L)
    (cond ((or (= n 0) (null? L)) '())
          (else (cons (car L) (firstN (- n 1) (cdr L)))))))

(define skipN
  (lambda (n L)
    (cond ((or (= n 0) (null? L)) L)
          (else (skipN (- n 1) (cdr L))))))

(define chunk
  (lambda (N L)
    (cond ((null? L) '())
          (else (cons (firstN N L) (chunk N (skipN N L)))))))

sumByKey

AL is a list of (key number) pairs, and the same key can appear several times. Write sumByKey, which returns one (key total) pair per key, where total is the sum of all its numbers. Keys appear in the order they first show up in AL.

(sumByKey '((a 1) (b 2) (a 3)))         ⇒ ((a 4) (b 2))
(sumByKey '((x 5)))                     ⇒ ((x 5))
(sumByKey '())                          ⇒ ()
(sumByKey '((a 1) (a 1) (a 1)))         ⇒ ((a 3))
(sumByKey '((b 2) (a 1) (b -2) (c 0)))  ⇒ ((b 0) (a 1) (c 0))

Not allowed: assoc, assq, assv, hash-update!, hash-set! or make-hash.

Show answer

Build a table as you go. For each pair, add its number to that key's total, or put the key at the END of the table if it's new. That keeps first-appearance order.

;; add n to key's total in the table; a new key goes at the end
(define addTo
  (lambda (table key n)
    (cond ((null? table) (list (list key n)))
          ((equal? key (car (car table)))
           (cons (list key (+ n (cadr (car table)))) (cdr table)))
          (else (cons (car table) (addTo (cdr table) key n))))))

(define build
  (lambda (AL table)
    (cond ((null? AL) table)
          (else (build (cdr AL) (addTo table (car (car AL)) (cadr (car AL))))))))

(define sumByKey
  (lambda (AL)
    (build AL '())))

flatten

Write flatten, which returns a flat list of all the non-list elements of L, at any depth, in left-to-right order.

(flatten '(1 (2 (3 4)) 5))  ⇒ (1 2 3 4 5)
(flatten '())               ⇒ ()
(flatten '((())))           ⇒ ()
(flatten '(a (b) ((c))))    ⇒ (a b c)

Not allowed: foldr, foldl, apply or flatten.

Show answer

The deep shape: if the first element is a list, flatten it and append it to the flattened rest. Otherwise cons it on. Empty inner lists contribute nothing.

(define flatten
  (lambda (L)
    (cond ((null? L) '())
          ((list? (car L)) (append (flatten (car L)) (flatten (cdr L))))
          (else (cons (car L) (flatten (cdr L)))))))

deepSum

Write deepSum, which returns the sum of all the numbers in L, however deeply nested.

(deepSum '(1 (2 3) ((4))))  ⇒ 10
(deepSum '())               ⇒ 0
(deepSum '(() (())))        ⇒ 0
(deepSum '(5))              ⇒ 5

Not allowed: foldr, foldl, apply or flatten.

Show answer

The deep shape with numbers: add the deepSum of a list element, or the number itself.

(define deepSum
  (lambda (L)
    (cond ((null? L) 0)
          ((list? (car L)) (+ (deepSum (car L)) (deepSum (cdr L))))
          (else (+ (car L) (deepSum (cdr L)))))))

countAtoms

Write countAtoms, which returns how many non-list elements are in L, at any depth.

(countAtoms '(a (b c) ((d))))  ⇒ 4
(countAtoms '())               ⇒ 0
(countAtoms '(() ()))          ⇒ 0
(countAtoms '(1 2))            ⇒ 2

Not allowed: foldr, foldl, apply, flatten or length.

Show answer

The deep shape: lists are searched inside, every non-list counts 1, and empty lists count nothing.

(define countAtoms
  (lambda (L)
    (cond ((null? L) 0)
          ((list? (car L)) (+ (countAtoms (car L)) (countAtoms (cdr L))))
          (else (+ 1 (countAtoms (cdr L)))))))

frequencies

Write frequencies, which returns a list of (element count) pairs, one for each different element of L, in the order each element first appears.

(frequencies '(a b a c b a))  ⇒ ((a 3) (b 2) (c 1))
(frequencies '())             ⇒ ()
(frequencies '(x))            ⇒ ((x 1))
(frequencies '(1 1 1))        ⇒ ((1 3))

Not allowed: foldr, foldl, apply, count, group-by or remove*.

Show answer

A table of (element count). Bump the count for each element, appending new elements at the end so the first-seen order is kept.

(define bump                             ; add 1 to x's count (new x goes at the end)
  (lambda (table x)
    (cond ((null? table) (list (list x 1)))
          ((equal? x (car (car table)))
           (cons (list x (+ 1 (cadr (car table)))) (cdr table)))
          (else (cons (car table) (bump (cdr table) x))))))

(define countAll
  (lambda (L table)
    (cond ((null? L) table)
          (else (countAll (cdr L) (bump table (car L)))))))

(define frequencies
  (lambda (L)
    (countAll L '())))

mostFrequent

Write mostFrequent, which returns the element that appears most often in the non-empty list L. If there's a tie, return the one that appears first.

(mostFrequent '(a b a c b a))  ⇒ a
(mostFrequent '(x y y x))      ⇒ x
(mostFrequent '(5))            ⇒ 5
(mostFrequent '(1 2 3 3))      ⇒ 3

Not allowed: foldr, foldl, apply, count, argmax or sort.

Show answer

Build the frequency table, then pick the pair with the biggest count. Replacing only on STRICTLY bigger keeps the earliest one on a tie.

(define bump
  (lambda (table x)
    (cond ((null? table) (list (list x 1)))
          ((equal? x (car (car table)))
           (cons (list x (+ 1 (cadr (car table)))) (cdr table)))
          (else (cons (car table) (bump (cdr table) x))))))

(define countAll                         ; ((element count) ...) in first-seen order
  (lambda (L table)
    (cond ((null? L) table)
          (else (countAll (cdr L) (bump table (car L)))))))

(define bestPair                         ; strictly bigger count wins, so ties keep the first
  (lambda (best pairs)
    (cond ((null? pairs) best)
          ((> (cadr (car pairs)) (cadr best)) (bestPair (car pairs) (cdr pairs)))
          (else (bestPair best (cdr pairs))))))

(define mostFrequent
  (lambda (L)
    (let ((table (countAll L '())))
      (car (bestPair (car table) (cdr table))))))

encodeRuns

Write encodeRuns, which turns each run of consecutive equal elements in L into a pair (element length).

(encodeRuns '(a a b c c c))  ⇒ ((a 2) (b 1) (c 3))
(encodeRuns '())             ⇒ ()
(encodeRuns '(x))            ⇒ ((x 1))
(encodeRuns '(a b a))        ⇒ ((a 1) (b 1) (a 1))

Not allowed: foldr, foldl, apply or group-by.

Show answer

Same helpers as longestRun: measure the front run, output (element length), then skip past the run.

(define runLength
  (lambda (L)
    (cond ((null? (cdr L)) 1)
          ((equal? (car L) (cadr L)) (+ 1 (runLength (cdr L))))
          (else 1))))

(define afterRun
  (lambda (L)
    (cond ((null? (cdr L)) '())
          ((equal? (car L) (cadr L)) (afterRun (cdr L)))
          (else (cdr L)))))

(define encodeRuns
  (lambda (L)
    (cond ((null? L) '())
          (else (cons (list (car L) (runLength L))
                      (encodeRuns (afterRun L)))))))

removeDeep

Write removeDeep, which returns L with every occurrence of the atom X removed, at any depth. Nested lists keep their shape, even if they become empty.

(removeDeep 'a '(a (b a) ((a c))))  ⇒ ((b) ((c)))
(removeDeep 'a '())                 ⇒ ()
(removeDeep 3 '(1 2))               ⇒ (1 2)
(removeDeep 'a '((a)))              ⇒ (())

Not allowed: foldr, foldl, apply, remove* or filter.

Show answer

The deep shape, but lists are REBUILT, not searched for a count. cons the cleaned sub-list back in, so the nesting shape survives even if it ends up empty.

(define removeDeep
  (lambda (X L)
    (cond ((null? L) '())
          ((list? (car L)) (cons (removeDeep X (car L)) (removeDeep X (cdr L))))
          ((equal? X (car L)) (removeDeep X (cdr L)))
          (else (cons (car L) (removeDeep X (cdr L)))))))

unzip

Write unzip, which takes a list of two-element lists and returns a list of two lists: all the first elements, and all the second elements.

(unzip '((1 a) (2 b) (3 c)))  ⇒ ((1 2 3) (a b c))
(unzip '())                   ⇒ (() ())
(unzip '((x y)))              ⇒ ((x) (y))
(unzip '((1 1) (2 2)))        ⇒ ((1 2) (1 2))

Not allowed: foldr, foldl, apply or map.

Show answer

Returns two lists. Unzip the rest, then put the first pair's car on one list and its cadr on the other.

(define unzip
  (lambda (L)
    (cond ((null? L) (list '() '()))
          (else (let ((r (unzip (cdr L))))
                  (list (cons (car (car L)) (car r))
                        (cons (cadr (car L)) (cadr r))))))))

longest

Write longest, which takes a list of lists and returns the longest one. If several are equally long, return the first of them. If L is empty, return '().

(longest '((1 5 4) (2 4 7 9 8) (1 2) (2 5 3 6 1)))  ⇒ (2 4 7 9 8)
(longest '((a) (b c) (a)))                          ⇒ (b c)
(longest '((hello) (fellow kids) (!)))              ⇒ (fellow kids)
(longest '())                                       ⇒ ()
(longest '(() ()))                                  ⇒ ()
Show answer

Find the longest of the rest and compare. >= keeps the earlier list on a tie, and the empty input gives '().

(define longest
  (lambda (L)
    (cond ((null? L) '())
          (else (let ((best (longest (cdr L))))
                  (if (>= (length (car L)) (length best)) (car L) best))))))

Mid to hard

myMap

Write myMap, which returns a new list where every element of L has had the function F applied to it. The built-in map is off-limits.

(myMap (lambda (X) (* X X)) '(1 2 3))  ⇒ (1 4 9)
(myMap car '((a 1) (b 2)))             ⇒ (a b)
(myMap even? '(1 2))                   ⇒ (#f #t)
(myMap (lambda (X) X) '())             ⇒ ()

Not allowed: map, for-each, append-map, filter-map, foldr or foldl.

Show answer

map written by hand: apply F to the first element and cons it onto the mapped rest.

(define myMap
  (lambda (F L)
    (cond ((null? L) '())
          (else (cons (F (car L)) (myMap F (cdr L)))))))

myFilter

Write myFilter, which returns the elements of L for which (P element) is true, in their original order. The built-in filter is off-limits.

(myFilter even? '(1 2 3 4))                  ⇒ (2 4)
(myFilter symbol? '(a 1 b 2))                ⇒ (a b)
(myFilter (lambda (X) (> X 10)) '(5 15 20))  ⇒ (15 20)
(myFilter odd? '())                          ⇒ ()

Not allowed: filter, remove, filter-not, filter-map, remf, foldr or foldl.

Show answer

filter written by hand: cons the element when (P element) is true, otherwise skip it.

(define myFilter
  (lambda (P L)
    (cond ((null? L) '())
          ((P (car L)) (cons (car L) (myFilter P (cdr L))))
          (else (myFilter P (cdr L))))))

anyOf

Write anyOf, which returns #t if at least one element of L makes P return true, and #f otherwise.

(anyOf even? '(1 3 4))                     ⇒ #t
(anyOf even? '(1 3))                       ⇒ #f
(anyOf even? '())                          ⇒ #f
(anyOf (lambda (X) (equal? X 'b)) '(a b))  ⇒ #t
(anyOf null? '((1) () (2)))                ⇒ #t

Not allowed: ormap, filter, member, memf, findf, count or andmap.

Show answer

Return #t at the first element that passes. An empty list gives #f.

(define anyOf
  (lambda (P L)
    (cond ((null? L) #f)
          ((P (car L)) #t)
          (else (anyOf P (cdr L))))))

myFoldr

Write myFoldr. It should work like this:

  • for the empty list, the answer is Init
  • otherwise, the answer is (F first-element answer-for-the-rest).

So (myFoldr + 0 L) behaves like sumList. The built-ins foldr, foldl and apply are off-limits.

(myFoldr + 0 '(1 2 3))                                    ⇒ 6
(myFoldr cons '() '(a b c))                               ⇒ (a b c)
(myFoldr (lambda (X Acc) (+ Acc 1)) 0 '(a b c d))         ⇒ 4
(myFoldr * 1 '())                                         ⇒ 1
(myFoldr (lambda (X Acc) (cons (* 2 X) Acc)) '() '(1 2))  ⇒ (2 4)

Not allowed: foldr, foldl or apply.

Show answer

The general pattern behind sumList and friends. The empty list gives Init. Otherwise combine the first element with the result for the rest: (F (car L) (myFoldr F Init (cdr L))).

(define myFoldr
  (lambda (F Init L)
    (cond ((null? L) Init)
          (else (F (car L) (myFoldr F Init (cdr L)))))))

applyN

Write applyN, which applies the function F to X, N times over. So (applyN F 3 X) is (F (F (F X))).

(applyN (lambda (X) (* 2 X)) 3 1)        ⇒ 8
(applyN cdr 2 '(a b c d))                ⇒ (c d)
(applyN (lambda (X) (+ X 1)) 0 5)        ⇒ 5
(applyN (lambda (L) (cons 'x L)) 3 '())  ⇒ (x x x)

Not allowed: compose, compose1 or make-list.

Show answer

Recursion on the count: 0 times leaves X unchanged. Otherwise apply F to the result of applying it N−1 times.

(define applyN
  (lambda (F N X)
    (cond ((= N 0) X)
          (else (F (applyN F (- N 1) X))))))

zipWith

A and B have the same length. Write zipWith, which returns a list where each element is F applied to the elements of A and B at that position.

(zipWith + '(1 2 3) '(10 20 30))                         ⇒ (11 22 33)
(zipWith list '(a b) '(1 2))                             ⇒ ((a 1) (b 2))
(zipWith max '(1 9) '(5 2))                              ⇒ (5 9)
(zipWith * '() '())                                      ⇒ ()
(zipWith (lambda (X Y) (equal? X Y)) '(a b c) '(a z c))  ⇒ (#t #f #t)

Not allowed: map or foldr.

Show answer

Walk both lists in step, calling F on the two fronts. addPairs is zipWith with +.

(define zipWith
  (lambda (F A B)
    (cond ((null? A) '())
          (else (cons (F (car A) (car B)) (zipWith F (cdr A) (cdr B)))))))

maxBy

L is non-empty. F turns each element into a number (its "score"). Write maxBy, which returns the element with the highest score. If several elements share the highest score, return the one that appears first.

(maxBy (lambda (X) X) '(3 9 2))                          ⇒ 9
(maxBy length '((a) (b c) ()))                           ⇒ (b c)
(maxBy abs '(-7 3 5))                                    ⇒ -7
(maxBy (lambda (P) (cadr P)) '((ann 3) (bob 8) (cy 8)))  ⇒ (bob 8)
(maxBy car '((5 x)))                                     ⇒ (5 x)

Not allowed: argmax, sort, argmin, foldl or foldr.

Show answer

Keep a best-so-far and replace it only when an element scores STRICTLY higher. That way ties keep the first. It returns the element, not its score.

(define bestOf                           ; best = winner so far
  (lambda (F best L)
    (cond ((null? L) best)
          ((> (F (car L)) (F best)) (bestOf F (car L) (cdr L)))   ; strictly better only
          (else (bestOf F best (cdr L))))))

(define maxBy
  (lambda (F L)
    (bestOf F (car L) (cdr L))))

keysWhere

AL is a list of (key value) pairs. Write keysWhere, which returns the keys whose value makes P return true, in their original order.

(keysWhere even? '((a 1) (b 2) (c 4)))         ⇒ (b c)
(keysWhere (lambda (V) (> V 100)) '((x 5)))    ⇒ ()
(keysWhere symbol? '((n 1) (m red) (k blue)))  ⇒ (m k)
(keysWhere even? '())                          ⇒ ()

Not allowed: filter, map, filter-map, filter-not or foldr.

Show answer

A hand-written filter on pairs: test the value (cadr pair) and keep the key (car pair).

(define keysWhere
  (lambda (P AL)
    (cond ((null? AL) '())
          ((P (cadr (car AL))) (cons (car (car AL)) (keysWhere P (cdr AL))))
          (else (keysWhere P (cdr AL))))))

makeAdder

Write makeAdder, which takes a number N and returns a function. That function takes one number and adds N to it.

So ((makeAdder 3) 4) is 7: (makeAdder 3) gives you a function, and the outer brackets call it with 4.

((makeAdder 3) 4)              ⇒ 7
((makeAdder -1) 1)             ⇒ 0
(map (makeAdder 10) '(1 2 3))  ⇒ (11 12 13)
(procedure? (makeAdder 5))     ⇒ #t
((makeAdder 0) 42)             ⇒ 42

Not allowed: curry or curryr.

Show answer

A closure: return a lambda that remembers N and adds it to whatever it's given.

(define makeAdder
  (lambda (N)
    (lambda (x)
      (+ x N))))

selectionSortBy

Write selectionSortBy, which sorts L using the comparison function C: when (C X Y) is true, X should come before Y. Use this plan:

  1. find the element that should come first (like your findBest)
  2. remove one copy of it from the list
  3. sort what's left, and put the best element in front.

The built-in sort is off-limits.

(selectionSortBy < '(3 1 2))
  ⇒ (1 2 3)
(selectionSortBy > '(3 1 2))
  ⇒ (3 2 1)
(selectionSortBy < '(2 1 2 1))
  ⇒ (1 1 2 2)
(selectionSortBy < '())
  ⇒ ()
(selectionSortBy (lambda (X Y) (< (cadr X) (cadr Y))) '((a 3) (b 1) (c 2)))
  ⇒ ((b 1) (c 2) (a 3))

Not allowed: sort, remove, argmin, argmax or remf.

Show answer

Find the element that should come first, put it in front, then sort the list with ONE copy of it removed. removeOne removes just one copy, so duplicates survive.

(define findFirst                        ; the element that should come first
  (lambda (C best L)
    (cond ((null? L) best)
          ((C (car L) best) (findFirst C (car L) (cdr L)))
          (else (findFirst C best (cdr L))))))

(define removeOne
  (lambda (x L)
    (cond ((null? L) '())
          ((equal? x (car L)) (cdr L))
          (else (cons (car L) (removeOne x (cdr L)))))))

(define selectionSortBy
  (lambda (C L)
    (cond ((null? L) '())
          (else (let ((best (findFirst C (car L) (cdr L))))
                  (cons best (selectionSortBy C (removeOne best L))))))))

applyAll

Fs is a list of one-argument functions. Write applyAll, which calls each function in Fs on the same value X and returns the list of results, in order.

(applyAll (list car cdr length) '(a b c))
  ⇒ (a (b c) 3)
(applyAll (list even? odd?) 4)
  ⇒ (#t #f)
(applyAll '() 5)
  ⇒ ()
(applyAll (list (lambda (X) (* X X)) abs (lambda (X) (- X))) -3)
  ⇒ (9 3 3)
(applyAll (list (lambda (L) (cons 0 L))) '(1))
  ⇒ ((0 1))

Not allowed: map.

Show answer

Walk the list of FUNCTIONS, calling each one on the same X.

(define applyAll
  (lambda (Fs X)
    (cond ((null? Fs) '())
          (else (cons ((car Fs) X) (applyAll (cdr Fs) X))))))

takeWhile

Write takeWhile, which returns the elements at the front of L for which P is true, stopping at the first element that fails. Nothing after that element is included, even if it would pass.

(takeWhile even? '(2 4 5 6))                ⇒ (2 4)
(takeWhile odd? '(2 3))                     ⇒ ()
(takeWhile even? '())                       ⇒ ()
(takeWhile (lambda (X) (< X 10)) '(1 5 9))  ⇒ (1 5 9)
(takeWhile symbol? '(a b 1 c))              ⇒ (a b)

Not allowed: takef, dropf, filter or splitf-at.

Show answer

Keep elements while P holds. At the first failure return '(), so nothing after it is included.

(define takeWhile
  (lambda (P L)
    (cond ((null? L) '())
          ((P (car L)) (cons (car L) (takeWhile P (cdr L))))
          (else '()))))                  ; first failure: stop completely

dropWhile

Write dropWhile, which removes elements from the front of L as long as P is true for them, and returns what's left, starting from the first element that fails.

(dropWhile even? '(2 4 5 6))                ⇒ (5 6)
(dropWhile odd? '(2 3))                     ⇒ (2 3)
(dropWhile even? '())                       ⇒ ()
(dropWhile (lambda (X) (< X 10)) '(1 5 9))  ⇒ ()
(dropWhile symbol? '(a b 1 c))              ⇒ (1 c)

Not allowed: dropf, takef, filter or splitf-at.

Show answer

Skip elements while P holds. At the first failure return the whole remaining list from there.

(define dropWhile
  (lambda (P L)
    (cond ((null? L) '())
          ((P (car L)) (dropWhile P (cdr L)))
          (else L))))

adjacentMap

Write adjacentMap, which calls the two-argument function F on every pair of neighbouring elements of L, as (F element next-element), and returns the list of results.

(adjacentMap (lambda (A B) (- B A)) '(1 4 9 16))  ⇒ (3 5 7)
(adjacentMap list '(a b c))                       ⇒ ((a b) (b c))
(adjacentMap + '(5))                              ⇒ ()
(adjacentMap + '())                               ⇒ ()
(adjacentMap equal? '(x x y))                     ⇒ (#t #f)

Not allowed: map.

Show answer

Call F on (car L) and (cadr L), then recurse on (cdr L), so every neighbouring pair is visited once. Fewer than two elements gives '().

(define adjacentMap
  (lambda (F L)
    (cond ((or (null? L) (null? (cdr L))) '())
          (else (cons (F (car L) (cadr L)) (adjacentMap F (cdr L)))))))

mapIndexed

Write mapIndexed, which works like myMap, except F takes two arguments: the position of the element (counting from 0) and the element itself, as (F position element).

(mapIndexed (lambda (I X) (* I X)) '(5 5 5))
  ⇒ (0 5 10)
(mapIndexed list '(a b c))
  ⇒ ((0 a) (1 b) (2 c))
(mapIndexed + '())
  ⇒ ()
(mapIndexed (lambda (I X) I) '(x y z w))
  ⇒ (0 1 2 3)
(mapIndexed (lambda (I X) (if (even? I) X 'skip)) '(a b c))
  ⇒ (a skip c)

Not allowed: map or build-list.

Show answer

Carry the position as an extra argument that goes up by 1 at each step, starting from 0.

(define mapFrom                          ; i = position of (car L)
  (lambda (F i L)
    (cond ((null? L) '())
          (else (cons (F i (car L)) (mapFrom F (+ i 1) (cdr L)))))))

(define mapIndexed
  (lambda (F L)
    (mapFrom F 0 L)))

flatMap

F takes one element and returns a list. Write flatMap, which calls F on every element of L and joins all the resulting lists into one list, in order.

(flatMap (lambda (X) (list X X)) '(1 2))
  ⇒ (1 1 2 2)
(flatMap (lambda (X) (if (even? X) (list X) '())) '(1 2 3 4))
  ⇒ (2 4)
(flatMap list '())
  ⇒ ()
(flatMap (lambda (L) L) '((a b) () (c)))
  ⇒ (a b c)
(flatMap (lambda (N) (list N (* N 10))) '(3))
  ⇒ (3 30)

Not allowed: append-map, map, apply, append*, flatten or filter-map.

Show answer

Like myMap, but each F result is a list, so append it instead of consing it.

(define flatMap
  (lambda (F L)
    (cond ((null? L) '())
          (else (append (F (car L)) (flatMap F (cdr L)))))))

pipeline

Fs is a list of one-argument functions. Write pipeline, which applies them to X one after another, from left to right: the first function to X, the second to that result, and so on.

(pipeline (list (lambda (X) (+ X 1)) (lambda (X) (* X 2))) 3)
  ⇒ 8
(pipeline (list cdr cdr car) '(a b c d))
  ⇒ c
(pipeline '() 42)
  ⇒ 42
(pipeline (list (lambda (L) (cons 0 L))) '(1))
  ⇒ (0 1)
(pipeline (list abs (lambda (X) (- X 1)) even?) -5)
  ⇒ #t

Not allowed: compose, compose1, foldl or foldr.

Show answer

Apply the first function to X, then pass the RESULT on with the remaining functions. No functions left means the current value is the answer.

(define pipeline
  (lambda (Fs X)
    (cond ((null? Fs) X)
          (else (pipeline (cdr Fs) ((car Fs) X))))))

iterateUntil

Write iterateUntil, which keeps applying F to X until P is true of the value, then returns that value. If P is already true of X, return X without calling F at all.

(iterateUntil (lambda (X) (* X 2)) (lambda (X) (> X 100)) 1)
  ⇒ 128
(iterateUntil cdr null? '(a b c))
  ⇒ ()
(iterateUntil (lambda (X) (+ X 1)) even? 4)
  ⇒ 4
(iterateUntil (lambda (X) (quotient X 10)) (lambda (X) (< X 10)) 98765)
  ⇒ 9
(iterateUntil (lambda (L) (cons 'x L)) (lambda (L) (= (length L) 3)) '())
  ⇒ (x x x)
Show answer

Check P BEFORE applying F. That way, if P is already true, F is never called.

(define iterateUntil
  (lambda (F P X)
    (cond ((P X) X)
          (else (iterateUntil F P (F X))))))

myFoldl

Write myFoldl, the left-to-right partner of myFoldr. Start with Init as the accumulator. Then go through L from left to right, and for each element X the accumulator becomes (F X accumulator). When the list runs out, return the accumulator.

So (myFoldl cons '() '(1 2 3)) is (cons 3 (cons 2 (cons 1 '()))), which is (3 2 1). The built-ins foldl, foldr and apply are off-limits.

(myFoldl + 0 '(1 2 3))                                ⇒ 6
(myFoldl cons '() '(1 2 3))                           ⇒ (3 2 1)
(myFoldl (lambda (X Acc) (list X Acc)) '() '(1 2 3))  ⇒ (3 (2 (1 ())))
(myFoldl * 1 '())                                     ⇒ 1
(myFoldl (lambda (X Acc) (max X Acc)) 0 '(4 9 2))     ⇒ 9

Not allowed: foldl, foldr, apply or reverse.

Show answer

The accumulator version of fold. Combine the first element INTO the accumulator, then continue with the rest. The final accumulator is the answer.

(define myFoldl
  (lambda (F Init L)
    (cond ((null? L) Init)
          (else (myFoldl F (F (car L) Init) (cdr L))))))   ; Init is the accumulator

myScan

Write myScan. It walks through L exactly like myFoldl: the accumulator starts as Init, and for each element X from left to right it becomes (F X accumulator). But instead of returning only the final accumulator, it returns the list of every accumulator value, starting with Init.

So (myScan + 0 '(1 2 3)) is (0 1 3 6).

(myScan + 0 '(1 2 3))      ⇒ (0 1 3 6)
(myScan * 1 '(2 3 4))      ⇒ (1 2 6 24)
(myScan + 0 '())           ⇒ (0)
(myScan cons '() '(a b))   ⇒ (() (a) (b a))
(myScan max 0 '(3 1 5 2))  ⇒ (0 3 3 5 5)

Not allowed: foldl, foldr, map or apply.

Show answer

Like myFoldl, but cons each accumulator value onto the output as you go, starting with Init.

(define myScan
  (lambda (F Init L)
    (cond ((null? L) (list Init))
          (else (cons Init (myScan F (F (car L) Init) (cdr L)))))))

uniqueBy

F turns each element into a key. Write uniqueBy, which keeps only the first element for each distinct key (compare keys with equal?). Everything that's kept stays in its original order.

(uniqueBy car '((a 1) (b 2) (a 3)))     ⇒ ((a 1) (b 2))
(uniqueBy (lambda (X) X) '(1 2 1 3 2))  ⇒ (1 2 3)
(uniqueBy even? '(1 3 2 5 4))           ⇒ (1 2)
(uniqueBy length '())                   ⇒ ()
(uniqueBy abs '(-2 2 3 -3 1))           ⇒ (-2 3 1)

Not allowed: remove-duplicates, filter, filter-not, remove*, remf or remove.

Show answer

Keep the first element, then remove every later element with the same key before continuing.

(define dropKey                          ; L without the elements whose key is k
  (lambda (F k L)
    (cond ((null? L) '())
          ((equal? (F (car L)) k) (dropKey F k (cdr L)))
          (else (cons (car L) (dropKey F k (cdr L)))))))

(define uniqueBy
  (lambda (F L)
    (cond ((null? L) '())
          (else (cons (car L)
                      (uniqueBy F (dropKey F (F (car L)) (cdr L))))))))

groupAdjacentBy

F turns each element into a key. Write groupAdjacentBy, which groups neighbouring elements that have equal keys (compare with equal?) into lists. The groups stay in order, and so do the elements inside them.

(groupAdjacentBy even? '(2 4 1 3 6))         ⇒ ((2 4) (1 3) (6))
(groupAdjacentBy (lambda (X) X) '(a a b a))  ⇒ ((a a) (b) (a))
(groupAdjacentBy car '((x 1) (x 2) (y 3)))   ⇒ (((x 1) (x 2)) ((y 3)))
(groupAdjacentBy abs '())                    ⇒ ()
(groupAdjacentBy abs '(-1 1 2))              ⇒ ((-1 1) (2))

Not allowed: group-by.

Show answer

Group the rest first. If the first element's key matches the key of the first group, join that group. Otherwise start a new group.

(define groupAdjacentBy
  (lambda (F L)
    (cond ((null? L) '())
          (else (let ((r (groupAdjacentBy F (cdr L))))   ; groups for the rest
                  (if (and (not (null? r))
                           (equal? (F (car L)) (F (car (car r)))))
                      (cons (cons (car L) (car r)) (cdr r))   ; join the first group
                      (cons (list (car L)) r)))))))           ; start a new group

countIf

Write countIf, which returns how many elements of L make the function P return true.

(countIf even? '(1 2 4))                    ⇒ 2
(countIf (lambda (X) (> X 10)) '(5 20 30))  ⇒ 2
(countIf odd? '())                          ⇒ 0
(countIf symbol? '(a 1 b))                  ⇒ 2

Not allowed: foldr, foldl, apply, count or filter.

Show answer

Count with any condition: add 1 when (P (car L)) holds.

(define countIf
  (lambda (P L)
    (cond ((null? L) 0)
          ((P (car L)) (+ 1 (countIf P (cdr L))))
          (else (countIf P (cdr L))))))

allOrdered

Write allOrdered, which returns #t if (CMP a b) is true for every pair of neighbouring elements a b in L.

(allOrdered < '(1 2 3))   ⇒ #t
(allOrdered < '(1 1 2))   ⇒ #f
(allOrdered <= '(1 1 2))  ⇒ #t
(allOrdered > '())        ⇒ #t
(allOrdered > '(5))       ⇒ #t

Not allowed: foldr, foldl, apply, sorted? or andmap.

Show answer

Check (CMP a b) on each neighbouring pair. Lists shorter than 2 are ordered automatically.

(define allOrdered
  (lambda (CMP L)
    (cond ((or (null? L) (null? (cdr L))) #t)
          ((CMP (car L) (cadr L)) (allOrdered CMP (cdr L)))
          (else #f))))

findBest

(BETTER a b) returns true if a is strictly better than b. Write findBest, which returns the best element of the non-empty list L. If there's a tie, return the earliest one.

(findBest > '(3 9 2))
  ⇒ 9
(findBest < '(3 9 2))
  ⇒ 2
(findBest (lambda (A B) (> (length A) (length B))) '((1) (1 2 3) (4 5)))
  ⇒ (1 2 3)
(findBest > '(4 4 1))
  ⇒ 4
(findBest > '(7))
  ⇒ 7

Not allowed: foldr, foldl, apply, argmax, argmin, sort, max or min.

Show answer

Best-so-far again. Replace only when the new element is strictly better, so ties keep the earliest.

(define bestSoFar
  (lambda (BETTER best L)
    (cond ((null? L) best)
          ((BETTER (car L) best) (bestSoFar BETTER (car L) (cdr L)))
          (else (bestSoFar BETTER best (cdr L))))))

(define findBest
  (lambda (BETTER L)
    (bestSoFar BETTER (car L) (cdr L))))

mergeBy

A and B are each sorted by CMP: (CMP x y) is true when x should come before y. Write mergeBy, which merges them into one sorted list. When neither front should come first, take from A first.

(mergeBy < '(1 4) '(2 3))
  ⇒ (1 2 3 4)
(mergeBy > '(9 5 1) '(8 2))
  ⇒ (9 8 5 2 1)
(mergeBy < '() '(1))
  ⇒ (1)
(mergeBy (lambda (X Y) (< (length X) (length Y))) '((1) (1 2 3)) '((7 8)))
  ⇒ ((1) (7 8) (1 2 3))
(mergeBy < '(1 2) '(1))
  ⇒ (1 1 2)

Not allowed: foldr, foldl, apply, sort, merge or append.

Show answer

Take from B only when B's front must come BEFORE A's front. Otherwise take from A, which gives A priority on ties.

(define mergeBy
  (lambda (CMP A B)
    (cond ((null? A) B)
          ((null? B) A)
          ((CMP (car B) (car A)) (cons (car B) (mergeBy CMP A (cdr B))))   ; B's front must come first
          (else (cons (car A) (mergeBy CMP (cdr A) B))))))               ; otherwise A wins

partitionBy

Write partitionBy, which returns a list of two lists: the elements of L that pass P, and the ones that don't, each in their original order.

(partitionBy even? '(1 2 3 4))  ⇒ ((2 4) (1 3))
(partitionBy even? '())         ⇒ (() ())
(partitionBy symbol? '(a 1 b))  ⇒ ((a b) (1))
(partitionBy odd? '(1 3))       ⇒ ((1 3) ())

Not allowed: foldr, foldl, apply, partition, filter or filter-not.

Show answer

Like splitEvenOdd with any test: the recursion returns (passes fails).

(define partitionBy
  (lambda (P L)
    (cond ((null? L) (list '() '()))
          (else (let ((r (partitionBy P (cdr L))))
                  (if (P (car L))
                      (list (cons (car L) (car r)) (cadr r))
                      (list (car r) (cons (car L) (cadr r)))))))))

countUntil

Write countUntil, which returns how many elements of L come before the first one that passes P. If none passes, return the length of L.

(countUntil even? '(1 3 4 5))  ⇒ 2
(countUntil even? '(2))        ⇒ 0
(countUntil even? '(1 3))      ⇒ 2
(countUntil even? '())         ⇒ 0

Not allowed: foldr, foldl, apply, length, index-where or takef.

Show answer

Stop at the first passing element, counting 0 there. Each element before it adds 1.

(define countUntil
  (lambda (P L)
    (cond ((null? L) 0)
          ((P (car L)) 0)
          (else (+ 1 (countUntil P (cdr L)))))))

memberBy

Write memberBy, which returns #t if (EQ X e) is true for some element e of L, and #f otherwise.

(memberBy = 2 '(1 2 3))
  ⇒ #t
(memberBy (lambda (A B) (= (abs A) (abs B))) -3 '(1 3))
  ⇒ #t
(memberBy = 9 '(1 2))
  ⇒ #f
(memberBy = 1 '())
  ⇒ #f
(memberBy (lambda (A B) (equal? (car A) (car B))) '(k 1) '((j 5) (k 9)))
  ⇒ #t

Not allowed: foldr, foldl, apply, member, memf or ormap.

Show answer

isMember with a custom equality test EQ instead of equal?.

(define memberBy
  (lambda (EQ X L)
    (cond ((null? L) #f)
          ((EQ X (car L)) #t)
          (else (memberBy EQ X (cdr L))))))

indexWhere

Write indexWhere, which returns the position (starting at 0) of the first element of L that passes P, or -1 if none does.

(indexWhere even? '(1 3 4 6))  ⇒ 2
(indexWhere even? '(2))        ⇒ 0
(indexWhere even? '(1 3))      ⇒ -1
(indexWhere even? '())         ⇒ -1

Not allowed: foldr, foldl, apply, index-where or index-of.

Show answer

indexOf with a test instead of a value, using the same "don't add 1 to −1" rule.

(define indexWhere
  (lambda (P L)
    (cond ((null? L) -1)
          ((P (car L)) 0)
          (else (let ((i (indexWhere P (cdr L))))
                  (if (= i -1) -1 (+ i 1)))))))

complement

Write complement, which takes a predicate P and returns a new predicate that is true exactly when P is false.

((complement even?) 3)                 ⇒ #t
((complement even?) 4)                 ⇒ #f
((complement null?) '(1))              ⇒ #t
(filter (complement odd?) '(1 2 3 4))  ⇒ (2 4)
Show answer

Return a lambda that calls P and flips the answer with not.

(define complement
  (lambda (P)
    (lambda (x)
      (not (P x)))))

curry2

Write curry2, which takes a two-argument function F and returns a function that takes the first argument and returns a function waiting for the second. So (((curry2 F) a) b) is (F a b).

(((curry2 +) 2) 3)             ⇒ 5
(((curry2 -) 10) 4)            ⇒ 6
(((curry2 cons) 'a) '(b))      ⇒ (a b)
(map ((curry2 *) 3) '(1 2 3))  ⇒ (3 6 9)
Show answer

Three nested lambdas. Each one takes one argument and remembers it, and the innermost finally calls F.

(define curry2
  (lambda (F)
    (lambda (a)
      (lambda (b)
        (F a b)))))

juxt

Write juxt, which takes two functions and returns a function of one argument x that returns the list ((F x) (G x)).

((juxt car cdr) '(1 2 3))                   ⇒ (1 (2 3))
((juxt even? odd?) 4)                       ⇒ (#t #f)
(map (juxt (lambda (x) (* x x)) -) '(1 2))  ⇒ ((1 -1) (4 -2))
((juxt length reverse) '(1 2))              ⇒ (2 (2 1))
Show answer

Return a lambda that calls both remembered functions on x and lists the two results.

(define juxt
  (lambda (F G)
    (lambda (x)
      (list (F x) (G x)))))

either

Write either, which takes two predicates and returns a predicate that is true when at least one of them is true.

((either even? negative?) -3)                ⇒ #t
((either even? negative?) 3)                 ⇒ #f
((either even? negative?) 4)                 ⇒ #t
(filter (either zero? positive?) '(-1 0 2))  ⇒ (0 2)
Show answer

Return a predicate that is (or (P x) (Q x)).

(define either
  (lambda (P Q)
    (lambda (x)
      (or (P x) (Q x)))))

compareBy

Write compareBy, which takes a key function F and returns a comparison function of two arguments: true when (F a) is less than (F b).

((compareBy length) '(1) '(1 2))  ⇒ #t
((compareBy length) '(1 2) '(1))  ⇒ #f
((compareBy car) '(5 x) '(2 y))   ⇒ #f
((compareBy -) 3 1)               ⇒ #t
Show answer

Return a two-argument function that compares the KEYS (F a) and (F b) with <.

(define compareBy
  (lambda (F)
    (lambda (a b)
      (< (F a) (F b)))))

splitWhen

Write splitWhen, which returns a list of two lists: the elements before the first one that satisfies P, and the rest (starting with that element).

(splitWhen even? '(1 3 4 5 6))  ⇒ ((1 3) (4 5 6))
(splitWhen even? '(2 3))        ⇒ (() (2 3))
(splitWhen even? '(1 3))        ⇒ ((1 3) ())
(splitWhen even? '())           ⇒ (() ())
Show answer

Two lists again. At the first element that passes, everything from there goes into the second list.

(define splitWhen
  (lambda (P L)
    (cond ((null? L) (list '() '()))
          ((P (car L)) (list '() L))
          (else (let ((r (splitWhen P (cdr L))))
                  (list (cons (car L) (car r)) (cadr r)))))))

tails

Write tails, which returns every suffix of L, longest first, ending with ().

(tails '(1 2 3))             ⇒ ((1 2 3) (2 3) (3) ())
(tails '())                  ⇒ (())
(tails '(a))                 ⇒ ((a) ())
(map length (tails '(x y)))  ⇒ (2 1 0)
Show answer

cons the whole list onto the tails of its cdr. The empty list's only tail is () itself.

(define tails
  (lambda (L)
    (cond ((null? L) (list '()))
          (else (cons L (tails (cdr L)))))))

countBy

Write countBy, which applies F to every element and returns a list of (key count) pairs: how many elements gave each key. Keys appear in the order they first show up.

(countBy even? '(1 2 3 4 5))                       ⇒ ((#f 3) (#t 2))
(countBy (lambda (x) (remainder x 3)) '(1 2 3 4))  ⇒ ((1 2) (2 1) (0 1))
(countBy length '((a) (b c) (d)))                  ⇒ ((1 2) (2 1))
(countBy car '())                                  ⇒ ()
Show answer

A table of (key count). Bump the count for each element's key (F x), adding new keys at the end.

(define bump                             ; add 1 to k's count; a new key goes at the end
  (lambda (table k)
    (cond ((null? table) (list (list k 1)))
          ((equal? k (car (car table)))
           (cons (list k (+ 1 (cadr (car table)))) (cdr table)))
          (else (cons (car table) (bump (cdr table) k))))))

(define countKeys
  (lambda (F L table)
    (cond ((null? L) table)
          (else (countKeys F (cdr L) (bump table (F (car L))))))))

(define countBy
  (lambda (F L)
    (countKeys F L '())))

zipWith3

Write zipWith3, which calls F on the first elements of A, B and C, then the second elements, and so on, stopping when any list runs out.

(zipWith3 + '(1 2) '(10 20) '(100 200))                   ⇒ (111 222)
(zipWith3 list '(a b c) '(1 2) '(x y z))                  ⇒ ((a 1 x) (b 2 y))
(zipWith3 + '() '(1) '(2))                                ⇒ ()
(zipWith3 (lambda (x y z) (* x (+ y z))) '(2) '(3) '(4))  ⇒ (14)
Show answer

Walk three lists in step and stop when ANY of them runs out.

(define zipWith3
  (lambda (F A B C)
    (cond ((or (null? A) (null? B) (null? C)) '())
          (else (cons (F (car A) (car B) (car C))
                      (zipWith3 F (cdr A) (cdr B) (cdr C)))))))

sumBy

Write sumBy, which returns the sum of (F x) over every element x of L.

(sumBy length '((a b) (c) ()))         ⇒ 3
(sumBy (lambda (x) (* x x)) '(1 2 3))  ⇒ 14
(sumBy car '((5 a) (7 b)))             ⇒ 12
(sumBy abs '())                        ⇒ 0

Not allowed: apply, foldr, foldl or reduce.

Show answer

Like sumList, but add (F x) instead of x.

(define sumBy
  (lambda (F L)
    (cond ((null? L) 0)
          (else (+ (F (car L)) (sumBy F (cdr L)))))))

insertionSortBy

Write insertionSortBy, which sorts L using the comparison LT ((LT a b) is true when a should come before b). Use insertion sort: sort the rest, then insert the first element where it belongs. Equal elements keep their order.

(insertionSortBy < '(3 1 2))
  ⇒ (1 2 3)
(insertionSortBy > '(3 1 2))
  ⇒ (3 2 1)
(insertionSortBy (lambda (a b) (< (length a) (length b))) '((a b) (c) (d e f)))
  ⇒ ((c) (a b) (d e f))
(insertionSortBy < '())
  ⇒ ()
(insertionSortBy (lambda (a b) (< (car a) (car b))) '((1 x) (0 y) (1 z)))
  ⇒ ((0 y) (1 x) (1 z))

Not allowed: sort, list-sort or sort!.

Show answer

Sort the rest, then insert the first element. To keep equal elements in their original order, the element only moves past things that must come strictly BEFORE it.

;; x came earlier than everything in S, so it only moves past
;; elements that must come strictly before it (keeps equal ones in order)
(define insertBy
  (lambda (LT x S)
    (cond ((null? S) (list x))
          ((LT (car S) x) (cons (car S) (insertBy LT x (cdr S))))
          (else (cons x S)))))

(define insertionSortBy
  (lambda (LT L)
    (cond ((null? L) '())
          (else (insertBy LT (car L) (insertionSortBy LT (cdr L)))))))

pairwise

Write pairwise, which returns (F a b) for every pair where a comes before b in L, ordered by the position of a, then of b.

(pairwise + '(1 2 3))     ⇒ (3 4 5)
(pairwise list '(a b c))  ⇒ ((a b) (a c) (b c))
(pairwise * '(5))         ⇒ ()
(pairwise - '(10 1 2))    ⇒ (9 8 -1)
Show answer

Pair the first element with everything after it, then do the same for the rest. append joins the batches in order.

(define pairwise
  (lambda (F L)
    (cond ((null? L) '())
          (else (append (map (lambda (b) (F (car L) b)) (cdr L))   ; car paired with everything after it
                        (pairwise F (cdr L)))))))

filterIndex

Write filterIndex, which keeps the elements of L whose POSITION (counting from 0) satisfies P.

(filterIndex even? '(a b c d e))             ⇒ (a c e)
(filterIndex odd? '(a b c d e))              ⇒ (b d)
(filterIndex (lambda (i) (> i 1)) '(x y z))  ⇒ (z)
(filterIndex even? '())                      ⇒ ()
Show answer

Carry the position along and test the POSITION with P, not the element.

(define keepFrom                         ; i = position of (car L)
  (lambda (P i L)
    (cond ((null? L) '())
          ((P i) (cons (car L) (keepFrom P (+ i 1) (cdr L))))
          (else (keepFrom P (+ i 1) (cdr L))))))

(define filterIndex
  (lambda (P L)
    (keepFrom P 0 L)))

cartesian

Write cartesian, which returns (F a b) for every a in A and every b in B: all of the first a's combinations, then the next a's, and so on.

(cartesian list '(1 2) '(a b))   ⇒ ((1 a) (1 b) (2 a) (2 b))
(cartesian + '(10 20) '(1 2 3))  ⇒ (11 12 13 21 22 23)
(cartesian list '() '(a))        ⇒ ()
(cartesian * '(2) '(3))          ⇒ (6)
Show answer

For each a, map over all of B, then append that batch with the batches for the remaining as.

(define cartesian
  (lambda (F A B)
    (cond ((null? A) '())
          (else (append (map (lambda (b) (F (car A) b)) B)
                        (cartesian F (cdr A) B))))))

deepMap

Write deepMap, which applies F to every non-list element anywhere in the nested list L, keeping the nesting exactly the same.

(deepMap (lambda (x) (* x 10)) '(1 (2 (3)) 4))  ⇒ (10 (20 (30)) 40)
(deepMap symbol? '(a (1 b) ()))                 ⇒ (#t (#f #t) ())
(deepMap - '((((5)))))                          ⇒ ((((-5))))
(deepMap - '())                                 ⇒ ()

Not allowed: flatten.

Show answer

The deep shape that rebuilds: map inside sub-lists and apply F to atoms, keeping the nesting.

(define deepMap
  (lambda (F L)
    (cond ((null? L) '())
          ((list? (car L)) (cons (deepMap F (car L)) (deepMap F (cdr L))))
          (else (cons (F (car L)) (deepMap F (cdr L)))))))

firstN

Write firstN, which returns the first N elements of L that satisfy P (fewer if there aren't that many).

(firstN even? 2 '(1 2 3 4 5 6))  ⇒ (2 4)
(firstN even? 5 '(1 2 3))        ⇒ (2)
(firstN odd? 0 '(1 3))           ⇒ ()
(firstN symbol? 2 '(1 a 2 b c))  ⇒ (a b)
Show answer

Filter that stops early: when N reaches 0 you're done, even if more elements would pass.

(define firstN
  (lambda (P N L)
    (cond ((or (= N 0) (null? L)) '())
          ((P (car L)) (cons (car L) (firstN P (- N 1) (cdr L))))
          (else (firstN P N (cdr L))))))

windows

Write windows, which returns every run of N neighbouring elements of L, from left to right.

(windows 2 '(1 2 3 4))                               ⇒ ((1 2) (2 3) (3 4))
(windows 3 '(a b c))                                 ⇒ ((a b c))
(windows 3 '(a b))                                   ⇒ ()
(map (lambda (w) (apply + w)) (windows 2 '(1 2 3)))  ⇒ (3 5)

Not allowed: take, list-head or list-tail.

Show answer

While at least N elements remain, take the first N as one window and slide along by one with cdr.

(define firstK
  (lambda (k L)
    (cond ((= k 0) '())
          (else (cons (car L) (firstK (- k 1) (cdr L)))))))

(define windows
  (lambda (N L)
    (cond ((< (length L) N) '())         ; not enough left for a window
          (else (cons (firstK N L) (windows N (cdr L)))))))

maxRunBy

Write maxRunBy, which returns the length of the longest run of neighbouring elements in L that all satisfy P.

(maxRunBy even? '(2 4 1 6 8 10 3))  ⇒ 3
(maxRunBy even? '(1 3))             ⇒ 0
(maxRunBy positive? '(1 2 3))       ⇒ 3
(maxRunBy even? '())                ⇒ 0
Show answer

Carry two numbers: the current run length and the best so far. A failing element finishes the current run, which then resets to 0.

;; cur = length of the run we're in now, best = longest finished run
(define runs
  (lambda (P L cur best)
    (cond ((null? L) (max cur best))
          ((P (car L)) (runs P (cdr L) (+ cur 1) best))
          (else (runs P (cdr L) 0 (max cur best))))))

(define maxRunBy
  (lambda (P L)
    (runs P L 0 0)))

unfold

Write unfold: starting from SEED, as long as (STOP seed) is false, output (F seed) and move on to (NEXT seed). Return the outputs as a list.

(unfold (lambda (x) (> x 5)) (lambda (x) (* x x)) (lambda (x) (+ x 1)) 1)
  ⇒ (1 4 9 16 25)
(unfold zero? (lambda (x) x) (lambda (x) (- x 1)) 3)
  ⇒ (3 2 1)
(unfold null? car cddr '(a b c d e f))
  ⇒ (a c e)
(unfold (lambda (x) #t) (lambda (x) x) (lambda (x) x) 0)
  ⇒ ()
Show answer

The opposite of a fold: generate a list from a seed. Stop when STOP holds, otherwise output (F seed) and continue from (NEXT seed).

(define unfold
  (lambda (STOP F NEXT SEED)
    (cond ((STOP SEED) '())
          (else (cons (F SEED) (unfold STOP F NEXT (NEXT SEED)))))))

positionsOf

Write positionsOf, which returns the positions (counting from 0) of every element of L that satisfies P.

(positionsOf even? '(1 2 3 4 6))  ⇒ (1 3 4)
(positionsOf symbol? '(a 1 b))    ⇒ (0 2)
(positionsOf even? '(1 3))        ⇒ ()
(positionsOf null? '(() (a) ()))  ⇒ (0 2)
Show answer

Carry the index along and output the index, not the element, whenever P holds.

(define positionsFrom                    ; i = position of (car L)
  (lambda (P i L)
    (cond ((null? L) '())
          ((P (car L)) (cons i (positionsFrom P (+ i 1) (cdr L))))
          (else (positionsFrom P (+ i 1) (cdr L))))))

(define positionsOf
  (lambda (P L)
    (positionsFrom P 0 L)))

Hard

quicksortBy

Write quicksortBy, which sorts L by comparison function C:

  • use (car L) as the pivot
  • the elements X of (cdr L) where (C X pivot) is true go into the "before" group; all the others go into the "after" group
  • the answer is: sorted "before", then the pivot, then sorted "after".

The built-in sort is off-limits.

(quicksortBy < '(3 1 4 1 5 9 2 6))
  ⇒ (1 1 2 3 4 5 6 9)
(quicksortBy > '(2 7 2))
  ⇒ (7 2 2)
(quicksortBy < '())
  ⇒ ()
(quicksortBy < '(5 5 5))
  ⇒ (5 5 5)
(quicksortBy (lambda (A B) (< (car A) (car B))) '((2 b) (1 a) (2 c)))
  ⇒ ((1 a) (2 b) (2 c))

Not allowed: sort.

Show answer

Pick (car L) as the pivot and split the rest with two filters: the elements that go before it, and everything else. Sort both groups the same way and append them around the pivot.

(define quicksortBy
  (lambda (C L)
    (cond ((null? L) '())
          (else (let ((pivot (car L)))
                  (append (quicksortBy C (filter (lambda (x) (C x pivot)) (cdr L)))
                          (list pivot)
                          (quicksortBy C (filter (lambda (x) (not (C x pivot))) (cdr L)))))))))

evalWith

An expression E is one of:

  • a number
  • a symbol (a variable)
  • a list (op left right) where op is the symbol +, - or *, and left/right are expressions.

Env is an association list giving each variable a value, like ((x 3) (y 4)). Write evalWith, which returns the value of E.

(evalWith '(+ x 1) '((x 5)))                    ⇒ 6
(evalWith '(* (+ x y) (- x y)) '((x 5) (y 3)))  ⇒ 16
(evalWith 7 '())                                ⇒ 7
(evalWith 'z '((z 10)))                         ⇒ 10
(evalWith '(- (* 2 a) (+ b b)) '((a 4) (b 1)))  ⇒ 6

Not allowed: eval.

Show answer

A tiny interpreter. Numbers are themselves, and symbols are looked up in the environment with assoc. For (op left right), evaluate both sides first, then apply the operator.

(define evalWith
  (lambda (E Env)
    (cond ((number? E) E)
          ((symbol? E) (cadr (assoc E Env)))          ; look the variable up
          (else (let ((op (car E))
                      (l (evalWith (cadr E) Env))
                      (r (evalWith (caddr E) Env)))
                  (cond ((equal? op '+) (+ l r))
                        ((equal? op '-) (- l r))
                        (else (* l r))))))))

deepReverse

Write deepReverse, which reverses L and every list nested inside it, at every level. The built-in reverse is off-limits.

(deepReverse '(1 (2 3) 4))        ⇒ (4 (3 2) 1)
(deepReverse '((a b) (c (d e))))  ⇒ (((e d) c) (b a))
(deepReverse '())                 ⇒ ()
(deepReverse '(1 2 3))            ⇒ (3 2 1)
(deepReverse '(((x y))))          ⇒ (((y x)))

Not allowed: reverse.

Show answer

An accumulator reverse, with one change: when an element is itself a list, deep-reverse it before pushing it onto the accumulator.

(define deepRev                          ; acc = reversed so far
  (lambda (L acc)
    (cond ((null? L) acc)
          ((list? (car L)) (deepRev (cdr L) (cons (deepReverse (car L)) acc)))
          (else (deepRev (cdr L) (cons (car L) acc))))))

(define deepReverse
  (lambda (L)
    (deepRev L '())))

rleDecode

L is a run-length encoding: a list of (count element) pairs. Write rleDecode, which expands it back into the full list. This is the reverse of the encode problem from the runs set.

(rleDecode '((3 a) (1 b) (2 c)))  ⇒ (a a a b c c)
(rleDecode '())                   ⇒ ()
(rleDecode '((1 x)))              ⇒ (x)
(rleDecode '((2 (1 2))))          ⇒ ((1 2) (1 2))
(rleDecode '((0 q) (2 r)))        ⇒ (r r)

Not allowed: make-list, build-list or append-map.

Show answer

Expand each (count element) into count copies with a small helper, then append the expansions in order. A count of 0 gives nothing.

(define copies
  (lambda (n x)
    (cond ((= n 0) '())
          (else (cons x (copies (- n 1) x))))))

(define rleDecode
  (lambda (L)
    (cond ((null? L) '())
          (else (append (copies (car (car L)) (cadr (car L)))
                        (rleDecode (cdr L)))))))

subsets

Write subsets, which returns a list of all subsets of L. Each subset keeps the elements in their original order. The subsets themselves can come in any order.

(subsets '())       ⇒ (())
(subsets '(a))      ⇒ (() (a))
(subsets '(a b))    ⇒ (() (b) (a) (a b))
(subsets '(1 2 3))  ⇒ (() (3) (2) (2 3) (1) (1 3) (1 2) (1 2 3))

The results can come in any order. Not allowed: combinations.

Show answer

Every subset of L either skips (car L) or includes it. So take all subsets of the rest, plus the same subsets with (car L) consed on. The empty list has one subset: ().

;; every subset of the rest, once without (car L) and once with it
(define subsets
  (lambda (L)
    (cond ((null? L) (list '()))
          (else (let ((rest (subsets (cdr L))))
                  (append rest
                          (map (lambda (s) (cons (car L) s)) rest)))))))

bstInsert

A binary search tree is either '() (empty) or a list (value left right), where left and right are trees. Smaller values live in the left subtree, everything else in the right.

Write bstInsert, which returns a new tree with the number N added in the right place. If N equals a node's value, it goes right.

(bstInsert 5 '())                       ⇒ (5 () ())
(bstInsert 3 '(5 () ()))                ⇒ (5 (3 () ()) ())
(bstInsert 8 '(5 (3 () ()) ()))         ⇒ (5 (3 () ()) (8 () ()))
(bstInsert 4 '(5 (3 () ()) (8 () ())))  ⇒ (5 (3 () (4 () ())) (8 () ()))
(bstInsert 5 '(5 () ()))                ⇒ (5 () (5 () ()))
Show answer

Trees are rebuilt, not changed. Smaller values go into a rebuilt LEFT subtree and everything else into a rebuilt RIGHT one. An empty tree becomes a new leaf (N () ()).

(define bstInsert
  (lambda (N T)
    (cond ((null? T) (list N '() '()))
          ((< N (car T)) (list (car T) (bstInsert N (cadr T)) (caddr T)))
          (else (list (car T) (cadr T) (bstInsert N (caddr T)))))))

bstToList

Using the same tree format as bstInsert, write bstToList, which returns all the values of a binary search tree in sorted order (left subtree, then the node, then the right subtree).

(bstToList '())                              ⇒ ()
(bstToList '(5 () ()))                       ⇒ (5)
(bstToList '(5 (3 () (4 () ())) (8 () ())))  ⇒ (3 4 5 8)
(bstToList '(2 (1 () ()) (3 () ())))         ⇒ (1 2 3)
(bstToList '(10 (5 (2 () ()) ()) ()))        ⇒ (2 5 10)

Not allowed: sort or flatten.

Show answer

In-order traversal: left subtree, then the node, then the right subtree, joined with append. In a BST this comes out sorted.

(define bstToList
  (lambda (T)
    (cond ((null? T) '())
          (else (append (bstToList (cadr T))
                        (list (car T))
                        (bstToList (caddr T)))))))

deepSubst

Write deepSubst, which replaces every Old in L with New, at any depth. Old is always a symbol or number. New can be anything, even a list.

(deepSubst 'a 'z '(a (b a) ((a))))  ⇒ (z (b z) ((z)))
(deepSubst 1 0 '(1 2 (1 (1))))      ⇒ (0 2 (0 (0)))
(deepSubst 'x 'y '())               ⇒ ()
(deepSubst 'q 'r '(a b))            ⇒ (a b)
(deepSubst 'a '(new) '(a (a)))      ⇒ ((new) ((new)))
Show answer

The deep rebuilding shape: recurse into sub-lists, and swap any atom equal to Old for New.

(define deepSubst
  (lambda (Old New L)
    (cond ((null? L) '())
          ((list? (car L)) (cons (deepSubst Old New (car L)) (deepSubst Old New (cdr L))))
          ((equal? (car L) Old) (cons New (deepSubst Old New (cdr L))))
          (else (cons (car L) (deepSubst Old New (cdr L)))))))

countChange

Write countChange, which returns how many different ways there are to make Amount cents from the coin values in Coins. You can use each coin as many times as you like, and the order of the coins doesn't matter (1+2 and 2+1 are the same way).

(countChange 5 '(1 2 5))           ⇒ 4
(countChange 0 '(1 2))             ⇒ 1
(countChange 3 '(2))               ⇒ 0
(countChange 10 '(5 2 1))          ⇒ 10
(countChange 7 '())                ⇒ 0
(countChange 100 '(50 25 10 5 1))  ⇒ 292
Show answer

Every way of making the amount either uses the first coin at least once (amount minus coin, same coins) or never uses it (same amount, other coins). Hitting exactly 0 is one way; going negative or running out of coins is zero ways.

;; ways that use the first coin at least once + ways that never use it
(define countChange
  (lambda (Amount Coins)
    (cond ((= Amount 0) 1)
          ((or (< Amount 0) (null? Coins)) 0)
          (else (+ (countChange (- Amount (car Coins)) Coins)
                   (countChange Amount (cdr Coins)))))))

transpose

A matrix M is a non-empty list of rows, all the same non-zero length. Write transpose, which turns rows into columns, just like in Matrix Algebra.

(transpose '((1 2 3) (4 5 6)))  ⇒ ((1 4) (2 5) (3 6))
(transpose '((1 2) (3 4)))      ⇒ ((1 3) (2 4))
(transpose '((a b c)))          ⇒ ((a) (b) (c))
(transpose '((1) (2) (3)))      ⇒ ((1 2 3))
(transpose '((7)))              ⇒ ((7))

Not allowed: apply.

Show answer

Column 1 is (map car M). Make it the first row, then transpose (map cdr M) for the remaining columns. Stop when the rows are empty.

(define transpose
  (lambda (M)
    (cond ((null? (car M)) '())          ; rows used up
          (else (cons (map car M)        ; first column becomes a row
                      (transpose (map cdr M)))))))

treeHeight

Trees here use the same format as bstInsert: '() or (value left right). Write treeHeight, which returns the number of levels in T. The empty tree has height 0, and a single node has height 1.

(treeHeight '())                              ⇒ 0
(treeHeight '(5 () ()))                       ⇒ 1
(treeHeight '(5 (3 () ()) (8 () ())))         ⇒ 2
(treeHeight '(5 (3 (1 () ()) ()) ()))         ⇒ 3
(treeHeight '(1 () (2 () (3 () (4 () ())))))  ⇒ 4
Show answer

An empty tree has height 0. A node is 1 taller than its taller subtree.

(define treeHeight
  (lambda (T)
    (cond ((null? T) 0)
          (else (+ 1 (max (treeHeight (cadr T)) (treeHeight (caddr T))))))))

mirror

Write mirror, which returns the mirror image of the tree T: at every node, the left and right subtrees swap places.

(mirror '())                                     ⇒ ()
(mirror '(5 () ()))                              ⇒ (5 () ())
(mirror '(5 (3 () ()) (8 () ())))                ⇒ (5 (8 () ()) (3 () ()))
(mirror '(1 (2 (3 () ()) ()) ()))                ⇒ (1 () (2 () (3 () ())))
(mirror '(4 (2 (1 () ()) (3 () ())) (6 () ())))  ⇒ (4 (6 () ()) (2 (3 () ()) (1 () ())))
Show answer

Rebuild each node with its subtrees swapped, after mirroring each of them.

(define mirror
  (lambda (T)
    (cond ((null? T) '())
          (else (list (car T) (mirror (caddr T)) (mirror (cadr T)))))))

treeMap

Write treeMap, which returns a tree with the same shape as T, but with F applied to every value.

(treeMap (lambda (X) (* X 10)) '(5 (3 () ()) (8 () ())))  ⇒ (50 (30 () ()) (80 () ()))
(treeMap (lambda (X) X) '())                              ⇒ ()
(treeMap even? '(1 (2 () ()) ()))                         ⇒ (#f (#t () ()) ())
(treeMap (lambda (X) (- X)) '(2 () (4 () ())))            ⇒ (-2 () (-4 () ()))
(treeMap list '(7 () ()))                                 ⇒ ((7) () ())

Not allowed: map.

Show answer

Rebuild each node with (F value) and the mapped subtrees, so the shape stays the same.

(define treeMap
  (lambda (F T)
    (cond ((null? T) '())
          (else (list (F (car T)) (treeMap F (cadr T)) (treeMap F (caddr T)))))))

toInfix

Expressions use the same format as evalWith: a number, a symbol, or (op left right). Write toInfix, which rewrites E so that every operator sits between its two arguments, the way you'd write it on paper.

(toInfix '(+ 1 2))              ⇒ (1 + 2)
(toInfix '(* (+ a b) c))        ⇒ ((a + b) * c)
(toInfix 5)                     ⇒ 5
(toInfix 'x)                    ⇒ x
(toInfix '(- (* 2 x) (+ y 1)))  ⇒ ((2 * x) - (y + 1))
Show answer

Atoms stay as they are. (op a b) becomes (a' op b'), where a' and b' are converted the same way.

(define toInfix
  (lambda (E)
    (cond ((not (list? E)) E)            ; a number or a variable
          (else (list (toInfix (cadr E)) (car E) (toInfix (caddr E)))))))

treeLevel

Write treeLevel, which returns the values at depth K of tree T, from left to right. The root is at depth 0, its children at depth 1, and so on.

(treeLevel 0 '(5 (3 () ()) (8 () ())))                ⇒ (5)
(treeLevel 1 '(5 (3 () ()) (8 () ())))                ⇒ (3 8)
(treeLevel 2 '(5 (3 (1 () ()) ()) (8 () (9 () ()))))  ⇒ (1 9)
(treeLevel 1 '())                                     ⇒ ()
(treeLevel 3 '(5 () ()))                              ⇒ ()
Show answer

Count K down as you go down the tree. When K is 0, this node is on the level you want. Collect left before right.

(define treeLevel
  (lambda (K T)
    (cond ((null? T) '())
          ((= K 0) (list (car T)))
          (else (append (treeLevel (- K 1) (cadr T))
                        (treeLevel (- K 1) (caddr T)))))))

pathSum

A leaf is a node whose left and right subtrees are both empty. Write pathSum, which returns #t if there's a path from the root down to a leaf whose values add up to exactly N, and #f otherwise. An empty tree has no paths.

(pathSum 8 '(5 (3 () ()) (8 () ())))          ⇒ #t
(pathSum 13 '(5 (3 () ()) (8 () ())))         ⇒ #t
(pathSum 5 '(5 (3 () ()) (8 () ())))          ⇒ #f
(pathSum 0 '())                               ⇒ #f
(pathSum 7 '(7 () ()))                        ⇒ #t
(pathSum 10 '(1 (2 (7 () ()) ()) (4 () ())))  ⇒ #t
Show answer

Subtract each node's value from N on the way down. At a LEAF, check whether what's left equals the leaf's value. An empty tree has no paths, so it's #f.

(define pathSum
  (lambda (N T)
    (cond ((null? T) #f)
          ((and (null? (cadr T)) (null? (caddr T))) (= N (car T)))   ; a leaf
          (else (or (pathSum (- N (car T)) (cadr T))
                    (pathSum (- N (car T)) (caddr T)))))))

listToBST

Write listToBST, which builds a binary search tree by inserting the numbers of L one at a time, from left to right, into an empty tree. Use the bstInsert rules: smaller goes left, equal or bigger goes right.

(listToBST '())         ⇒ ()
(listToBST '(5))        ⇒ (5 () ())
(listToBST '(5 3 8))    ⇒ (5 (3 () ()) (8 () ()))
(listToBST '(5 3 8 4))  ⇒ (5 (3 () (4 () ())) (8 () ()))
(listToBST '(1 2 3))    ⇒ (1 () (2 () (3 () ())))
(listToBST '(2 2))      ⇒ (2 () (2 () ()))

Not allowed: sort.

Show answer

Insert the numbers one at a time, left to right, carrying the tree built so far as an accumulator.

(define bstInsert
  (lambda (N T)
    (cond ((null? T) (list N '() '()))
          ((< N (car T)) (list (car T) (bstInsert N (cadr T)) (caddr T)))
          (else (list (car T) (cadr T) (bstInsert N (caddr T)))))))

(define insertAll                        ; tree = the tree built so far
  (lambda (L tree)
    (cond ((null? L) tree)
          (else (insertAll (cdr L) (bstInsert (car L) tree))))))

(define listToBST
  (lambda (L)
    (insertAll L '())))

binaryStrings

Write binaryStrings, which returns a list of all lists of length N made of 0s and 1s. The lists can come in any order.

(binaryStrings 0)  ⇒ (())
(binaryStrings 1)  ⇒ ((0) (1))
(binaryStrings 2)  ⇒ ((0 0) (0 1) (1 0) (1 1))
(binaryStrings 3)  ⇒ ((0 0 0) (0 0 1) (0 1 0) (0 1 1) (1 0 0) (1 0 1) (1 1 0) (1 1 1))

The results can come in any order. Not allowed: cartesian-product, permutations or combinations.

Show answer

Every string of length N is a 0 or a 1 in front of a string of length N−1. Length 0 has exactly one string: ().

(define binaryStrings
  (lambda (N)
    (cond ((= N 0) (list '()))
          (else (let ((shorter (binaryStrings (- N 1))))
                  (append (map (lambda (s) (cons 0 s)) shorter)
                          (map (lambda (s) (cons 1 s)) shorter)))))))

canSum

L is a list of positive numbers. Write canSum, which returns #t if some of the numbers in L (each used at most once) add up to exactly N, and #f otherwise. Using no numbers at all adds up to 0.

(canSum 7 '(2 3 5))     ⇒ #t
(canSum 4 '(3 5))       ⇒ #f
(canSum 0 '(1 2))       ⇒ #t
(canSum 3 '())          ⇒ #f
(canSum 6 '(3))         ⇒ #f
(canSum 10 '(1 2 3 4))  ⇒ #t

Not allowed: combinations or permutations.

Show answer

Each number is either used or not. Reaching exactly 0 is success; going negative or running out of numbers is failure.

;; either use (car L) or don't
(define canSum
  (lambda (N L)
    (cond ((= N 0) #t)
          ((or (< N 0) (null? L)) #f)
          (else (or (canSum (- N (car L)) (cdr L))
                    (canSum N (cdr L)))))))

countSubsetsSum

L is a list of positive numbers. Write countSubsetsSum, which returns how many different subsets of L add up to exactly N. Each number can be used at most once, and numbers in different positions count as different, even if they're equal.

(countSubsetsSum 5 '(1 2 3 4))  ⇒ 2
(countSubsetsSum 0 '(1 2))      ⇒ 1
(countSubsetsSum 4 '())         ⇒ 0
(countSubsetsSum 3 '(1 1 2))    ⇒ 2
(countSubsetsSum 10 '(5 5 5))   ⇒ 3
(countSubsetsSum 9 '(2 4 6))    ⇒ 0

Not allowed: combinations or permutations.

Show answer

Like canSum, but add up the counts from "use it" and "skip it" instead of oring them. At the end of the list, count 1 only if the target is exactly 0.

;; subsets that use (car L) + subsets that don't
(define countSubsetsSum
  (lambda (N L)
    (cond ((null? L) (if (= N 0) 1 0))
          (else (+ (countSubsetsSum (- N (car L)) (cdr L))
                   (countSubsetsSum N (cdr L)))))))

interleavings

Write interleavings, which returns all the ways to merge A and B into one list, where the elements of A stay in their order and the elements of B stay in theirs. The merged lists can come in any order.

(interleavings '(1) '(a))      ⇒ ((1 a) (a 1))
(interleavings '() '(x y))     ⇒ ((x y))
(interleavings '() '())        ⇒ (())
(interleavings '(1 2) '(a))    ⇒ ((1 2 a) (1 a 2) (a 1 2))
(interleavings '(1 2) '(a b))  ⇒ ((1 2 a b) (1 a 2 b) (1 a b 2) (a 1 2 b) (a 1 b 2) (a b 1 2))

The results can come in any order. Not allowed: permutations or cartesian-product.

Show answer

The merged list starts with either A's first element or B's. Recurse for each choice and combine. If one list is empty, the only merge is the other list.

;; the merged list starts with either A's first element or B's
(define interleavings
  (lambda (A B)
    (cond ((null? A) (list B))
          ((null? B) (list A))
          (else (append (map (lambda (m) (cons (car A) m)) (interleavings (cdr A) B))
                        (map (lambda (m) (cons (car B) m)) (interleavings A (cdr B))))))))

maxSubsetSum

L is a list of positive numbers. Write maxSubsetSum, which returns the biggest total you can make by adding up some of the numbers in L (each at most once) without going over Limit. If nothing fits, the answer is 0.

(maxSubsetSum 12 '(3 4 8))      ⇒ 12
(maxSubsetSum 10 '(6 7 3))      ⇒ 10
(maxSubsetSum 5 '(6 7))         ⇒ 0
(maxSubsetSum 9 '())            ⇒ 0
(maxSubsetSum 100 '(10 20 30))  ⇒ 60
(maxSubsetSum 11 '(5 5 5 2))    ⇒ 10

Not allowed: combinations, sort, argmax or apply.

Show answer

For each number that still fits, compare "take it" (its value + the best from the rest with a smaller limit) with "skip it". Numbers that don't fit are skipped.

(define maxSubsetSum
  (lambda (Limit L)
    (cond ((null? L) 0)
          ((> (car L) Limit) (maxSubsetSum Limit (cdr L)))     ; can't use it
          (else (max (+ (car L) (maxSubsetSum (- Limit (car L)) (cdr L)))   ; use it
                     (maxSubsetSum Limit (cdr L)))))))                       ; skip it

treeSum

Trees use the same format as bstInsert: '() (empty) or a list (value left right). Write treeSum, which returns the sum of all the values in T.

(treeSum '())                              ⇒ 0
(treeSum '(5 () ()))                       ⇒ 5
(treeSum '(1 (2 () ()) (3 (4 () ()) ())))  ⇒ 10
(treeSum '(-1 (1 () ()) ()))               ⇒ 0

Not allowed: foldr, foldl, apply or flatten.

Show answer

Node value + left sum + right sum. The empty tree sums to 0.

(define treeSum
  (lambda (T)
    (cond ((null? T) 0)
          (else (+ (car T) (treeSum (cadr T)) (treeSum (caddr T)))))))

countLeaves

Trees use the same format as bstInsert: '() (empty) or a list (value left right). A leaf is a node whose left and right subtrees are both empty. Write countLeaves, which returns how many leaves T has.

(countLeaves '())                              ⇒ 0
(countLeaves '(5 () ()))                       ⇒ 1
(countLeaves '(1 (2 () ()) (3 (4 () ()) ())))  ⇒ 2
(countLeaves '(1 (2 (3 () ()) ()) ()))         ⇒ 1

Not allowed: foldr, foldl or apply.

Show answer

A node with two empty children counts 1. Otherwise add up the leaves in both subtrees.

(define countLeaves
  (lambda (T)
    (cond ((null? T) 0)
          ((and (null? (cadr T)) (null? (caddr T))) 1)
          (else (+ (countLeaves (cadr T)) (countLeaves (caddr T)))))))

bstContains

Trees use the same format as bstInsert: '() (empty) or a list (value left right). T is a binary search tree (smaller values on the left). Write bstContains, which returns #t if N is in T. Search only the side that could contain it.

(bstContains 4 '(5 (3 () (4 () ())) (8 () ())))  ⇒ #t
(bstContains 7 '(5 (3 () ()) (8 () ())))         ⇒ #f
(bstContains 1 '())                              ⇒ #f
(bstContains 5 '(5 () ()))                       ⇒ #t

Not allowed: foldr, foldl, apply, flatten or member.

Show answer

Uses the BST ordering: go left if N is smaller, right if bigger, and stop when you find it or hit an empty tree.

(define bstContains
  (lambda (N T)
    (cond ((null? T) #f)
          ((= N (car T)) #t)
          ((< N (car T)) (bstContains N (cadr T)))
          (else (bstContains N (caddr T))))))

bstMin

Trees use the same format as bstInsert: '() (empty) or a list (value left right). T is a non-empty binary search tree. Write bstMin, which returns its smallest value.

(bstMin '(5 (3 (1 () ()) ()) (8 () ())))  ⇒ 1
(bstMin '(5 () ()))                       ⇒ 5
(bstMin '(5 () (8 () ())))                ⇒ 5
(bstMin '(10 (6 () (7 () ())) ()))        ⇒ 6

Not allowed: foldr, foldl, apply, min or flatten.

Show answer

The smallest value is as far LEFT as you can go: follow left children until there are none.

(define bstMin
  (lambda (T)
    (cond ((null? (cadr T)) (car T))     ; nothing smaller on the left
          (else (bstMin (cadr T))))))

treeEqual

Trees use the same format as bstInsert: '() (empty) or a list (value left right). Write treeEqual, which returns #t if trees A and B have the same shape and the same numbers in the same places. equal? is off-limits.

(treeEqual '(1 (2 () ()) ()) '(1 (2 () ()) ()))  ⇒ #t
(treeEqual '(1 (2 () ()) ()) '(1 () (2 () ())))  ⇒ #f
(treeEqual '() '())                              ⇒ #t
(treeEqual '(1 () ()) '())                       ⇒ #f
(treeEqual '(1 () ()) '(2 () ()))                ⇒ #f

Not allowed: foldr, foldl, apply, equal?, eqv? or eq?.

Show answer

Both empty: equal. One empty: not equal. Otherwise the values must be = and both pairs of subtrees must match.

(define treeEqual
  (lambda (A B)
    (cond ((and (null? A) (null? B)) #t)
          ((or (null? A) (null? B)) #f)
          (else (and (= (car A) (car B))
                     (treeEqual (cadr A) (cadr B))
                     (treeEqual (caddr A) (caddr B)))))))

climbStairs

You climb a staircase of N steps, taking 1 or 2 steps at a time. Write climbStairs, which returns how many different ways there are to reach the top (N ≥ 0).

(climbStairs 0)   ⇒ 1
(climbStairs 1)   ⇒ 1
(climbStairs 3)   ⇒ 3
(climbStairs 5)   ⇒ 8
(climbStairs 10)  ⇒ 89
Show answer

The first move is either 1 step or 2 steps, so ways(N) = ways(N−1) + ways(N−2). This is the Fibonacci pattern.

;; the first move is either 1 step or 2 steps
(define climbStairs
  (lambda (N)
    (cond ((<= N 1) 1)
          (else (+ (climbStairs (- N 1)) (climbStairs (- N 2)))))))

countPartitions

A partition of N is a way of writing it as a sum of positive whole numbers, ignoring order (so 3+1 and 1+3 are the same). Write countPartitions, which returns how many partitions N ≥ 0 has.

(countPartitions 4)   ⇒ 5
(countPartitions 1)   ⇒ 1
(countPartitions 0)   ⇒ 1
(countPartitions 5)   ⇒ 7
(countPartitions 10)  ⇒ 42
Show answer

Count partitions of n whose parts are at most k: either use a k (n−k, still at most k) or don't use k at all (at most k−1). It's countChange with coins 1 to n.

;; partitions of n using parts no bigger than k
;; = those that use a k + those that don't (like countChange with coins 1..k)
(define parts
  (lambda (n k)
    (cond ((= n 0) 1)
          ((or (< n 0) (= k 0)) 0)
          (else (+ (parts (- n k) k) (parts n (- k 1)))))))

(define countPartitions
  (lambda (N)
    (parts N N)))

treeDepthOf

Trees use the same format as bstInsert: '() (empty) or a list (value left right). This tree is NOT a search tree, so X could be anywhere. Write treeDepthOf, which returns the depth of X (the root is depth 0), or -1 if it isn't in T. Values are all different.

(treeDepthOf 4 '(1 (2 () ()) (3 (4 () ()) ())))  ⇒ 2
(treeDepthOf 1 '(1 (2 () ()) ()))                ⇒ 0
(treeDepthOf 9 '(1 (2 () ()) ()))                ⇒ -1
(treeDepthOf 5 '())                              ⇒ -1
(treeDepthOf 2 '(1 (2 () ()) (3 () ())))         ⇒ 1

Not allowed: foldr, foldl, apply or flatten.

Show answer

Search the left subtree first, then the right. A depth found below gets +1 for this level, but −1 ("not found") is passed straight up.

(define treeDepthOf
  (lambda (X T)
    (cond ((null? T) -1)
          ((equal? X (car T)) 0)
          (else (let ((l (treeDepthOf X (cadr T))))
                  (if (not (= l -1))
                      (+ l 1)
                      (let ((r (treeDepthOf X (caddr T))))
                        (if (= r -1) -1 (+ r 1)))))))))

Very hard

permutations

L has no repeated elements. Write permutations, which returns a list of all possible orderings of L. The orderings can come in any order.

(permutations '())       ⇒ (())
(permutations '(a))      ⇒ ((a))
(permutations '(a b))    ⇒ ((a b) (b a))
(permutations '(1 2 3))  ⇒ ((1 2 3) (1 3 2) (2 1 3) (2 3 1) (3 1 2) (3 2 1))

The results can come in any order. Not allowed: permutations.

Show answer

For each element x, put x in front of every permutation of the other elements. The empty list has exactly one permutation: ().

(define removeOne
  (lambda (x L)
    (cond ((null? L) '())
          ((equal? x (car L)) (cdr L))
          (else (cons (car L) (removeOne x (cdr L)))))))

;; for each x: put x in front of every ordering of the others
(define permutations
  (lambda (L)
    (cond ((null? L) (list '()))
          (else (apply append
                       (map (lambda (x)
                              (map (lambda (p) (cons x p))
                                   (permutations (removeOne x L))))
                            L))))))

combinations

Write combinations, which returns every way of choosing K elements from L, each one keeping the original order. The combinations can come in any order.

(combinations 2 '(a b c))    ⇒ ((a b) (a c) (b c))
(combinations 0 '(a b))      ⇒ (())
(combinations 3 '(a b))      ⇒ ()
(combinations 1 '(x y))      ⇒ ((x) (y))
(combinations 2 '(1 2 3 4))  ⇒ ((1 2) (1 3) (1 4) (2 3) (2 4) (3 4))

The results can come in any order. Not allowed: combinations.

Show answer

Either take (car L) and choose K−1 more from the rest, or skip it and choose K from the rest. Choosing 0 gives (()); running out of list gives no combinations.

;; choose (car L) and K-1 from the rest, or skip it and choose K from the rest
(define combinations
  (lambda (K L)
    (cond ((= K 0) (list '()))
          ((null? L) '())
          (else (append (map (lambda (c) (cons (car L) c))
                             (combinations (- K 1) (cdr L)))
                        (combinations K (cdr L)))))))

derive

Expressions are numbers, symbols, (+ A B) or (* A B). Write derive, which differentiates E with respect to the variable V, using exactly these rules and no simplification:

  • a number → 0
  • the symbol V → 1
  • any other symbol → 0
  • (+ A B) → (+ A' B')
  • (* A B) → (+ (* A B') (* A' B))

where A' means the derivative of A.

(derive 5 'x)               ⇒ 0
(derive 'x 'x)              ⇒ 1
(derive 'y 'x)              ⇒ 0
(derive '(+ x 3) 'x)        ⇒ (+ 1 0)
(derive '(* x x) 'x)        ⇒ (+ (* x 1) (* 1 x))
(derive '(* 2 (+ x y)) 'x)  ⇒ (+ (* 2 (+ 1 0)) (* 0 (+ x y)))

Not allowed: eval.

Show answer

Apply the rules exactly as written, recursing into sub-expressions: numbers and other symbols give 0, the variable gives 1, sums differentiate term by term, and products use the product rule.

(define derive
  (lambda (E V)
    (cond ((number? E) 0)
          ((symbol? E) (if (equal? E V) 1 0))
          (else (let ((A (cadr E))
                      (B (caddr E)))
                  (cond ((equal? (car E) '+)
                         (list '+ (derive A V) (derive B V)))
                        (else                          ; product rule
                         (list '+ (list '* A (derive B V))
                                  (list '* (derive A V) B)))))))))

simplify

Expressions are numbers, symbols, (+ A B) or (* A B). Write simplify. First simplify A and B, then apply the first rule that matches:

  • both are numbers → compute the result
  • (+ 0 X) or (+ X 0) → X
  • (* 0 X) or (* X 0) → 0
  • (* 1 X) or (* X 1) → X
  • otherwise → rebuild (op A B) from the simplified parts.

Numbers and symbols are already simple. Try (simplify (derive '(* x x) 'x)) once both are done.

(simplify '(+ x 0))              ⇒ x
(simplify '(* 1 (+ y 0)))        ⇒ y
(simplify '(+ 2 3))              ⇒ 5
(simplify '(* (+ 1 1) x))        ⇒ (* 2 x)
(simplify '(+ (* x 1) (* 1 x)))  ⇒ (+ x x)
(simplify 'z)                    ⇒ z
(simplify '(* 0 (+ a b)))        ⇒ 0

Not allowed: eval.

Show answer

Simplify the two parts FIRST, then check the rules in order. If both parts are numbers, calculate; 0 and 1 cancel where they should; otherwise rebuild the expression.

(define simplify
  (lambda (E)
    (cond ((not (list? E)) E)
          (else
           (let ((op (car E))
                 (a (simplify (cadr E)))
                 (b (simplify (caddr E))))
             (cond ((and (number? a) (number? b))
                    (if (equal? op '+) (+ a b) (* a b)))
                   ((and (equal? op '+) (equal? a 0)) b)
                   ((and (equal? op '+) (equal? b 0)) a)
                   ((and (equal? op '*) (or (equal? a 0) (equal? b 0))) 0)
                   ((and (equal? op '*) (equal? a 1)) b)
                   ((and (equal? op '*) (equal? b 1)) a)
                   (else (list op a b))))))))

matrixMultiply

Matrices are lists of rows. The number of columns of A equals the number of rows of B. Write matrixMultiply, which returns the matrix product AB.

(matrixMultiply '((1 2) (3 4)) '((5 6) (7 8)))  ⇒ ((19 22) (43 50))
(matrixMultiply '((1 0) (0 1)) '((9 8) (7 6)))  ⇒ ((9 8) (7 6))
(matrixMultiply '((1 2 3)) '((4) (5) (6)))      ⇒ ((32))
(matrixMultiply '((2) (3)) '((1 4)))            ⇒ ((2 8) (3 12))

Not allowed: apply.

Show answer

Turn B's columns into rows with transpose. Then each entry is the dot product of a row of A with a column of B.

(define transpose
  (lambda (M)
    (cond ((null? (car M)) '())
          (else (cons (map car M) (transpose (map cdr M)))))))

(define dotP
  (lambda (u v)
    (cond ((null? u) 0)
          (else (+ (* (car u) (car v)) (dotP (cdr u) (cdr v)))))))

(define matrixMultiply
  (lambda (A B)
    (let ((cols (transpose B)))
      (map (lambda (row)
             (map (lambda (col) (dotP row col)) cols))
           A))))

evalRPN

Reverse Polish notation puts the operator after its two operands: (3 4 +) means 3 + 4, and (3 4 + 2 *) means (3 + 4) × 2. Write evalRPN, which evaluates a well-formed RPN list using +, - and *.

(evalRPN '(3 4 +))              ⇒ 7
(evalRPN '(3 4 + 2 *))          ⇒ 14
(evalRPN '(5 1 2 + 4 * + 3 -))  ⇒ 14
(evalRPN '(42))                 ⇒ 42
(evalRPN '(2 3 4 * -))          ⇒ -10
(evalRPN '(10 3 -))             ⇒ 7

Not allowed: eval.

Show answer

Uses a stack. Numbers are pushed. An operator pops the top two, the TOP being the right-hand operand, and pushes the result. At the end the answer is the only thing left.

;; stack: most recent number first
(define rpn
  (lambda (L stack)
    (cond ((null? L) (car stack))
          ((number? (car L)) (rpn (cdr L) (cons (car L) stack)))
          (else (let ((b (car stack))            ; top of stack is the RIGHT operand
                      (a (cadr stack))
                      (op (car L)))
                  (rpn (cdr L)
                       (cons (cond ((equal? op '+) (+ a b))
                                   ((equal? op '-) (- a b))
                                   (else (* a b)))
                             (cddr stack))))))))

(define evalRPN
  (lambda (L)
    (rpn L '())))

treePaths

Using the (value left right) tree format, write treePaths, which returns every path from the root down to a leaf (a node whose two children are both empty). Paths through the left subtree come before paths through the right.

(treePaths '())                              ⇒ ()
(treePaths '(1 () ()))                       ⇒ ((1))
(treePaths '(1 (2 () ()) (3 () ())))         ⇒ ((1 2) (1 3))
(treePaths '(1 (2 (4 () ()) ()) (3 () ())))  ⇒ ((1 2 4) (1 3))
(treePaths '(5 () (7 (6 () ()) (9 () ()))))  ⇒ ((5 7 6) (5 7 9))
Show answer

A leaf gives one path containing just itself. Otherwise collect the paths from both subtrees and cons the current value onto each.

(define treePaths
  (lambda (T)
    (cond ((null? T) '())
          ((and (null? (cadr T)) (null? (caddr T))) (list (list (car T))))   ; a leaf
          (else (map (lambda (p) (cons (car T) p))
                     (append (treePaths (cadr T)) (treePaths (caddr T))))))))

lcsLength

A subsequence keeps elements in order but may skip some: (a c) is a subsequence of (a b c). Write lcsLength, which returns the length of the longest common subsequence of A and B.

(lcsLength '(a b c d) '(a c d))            ⇒ 3
(lcsLength '(a b c) '(d e f))              ⇒ 0
(lcsLength '() '(a))                       ⇒ 0
(lcsLength '(1 2 3 2 4 1) '(2 4 3 1 2 1))  ⇒ 4
(lcsLength '(x y x) '(x x))                ⇒ 2
Show answer

If the fronts match, they're part of the answer: 1 + the LCS of the rests. If not, drop one front or the other and take whichever gives the longer result.

(define lcsLength
  (lambda (A B)
    (cond ((or (null? A) (null? B)) 0)
          ((equal? (car A) (car B)) (+ 1 (lcsLength (cdr A) (cdr B))))
          (else (max (lcsLength (cdr A) B)       ; drop from A
                     (lcsLength A (cdr B)))))))  ; or drop from B

groupBy

Write groupBy, which groups the elements of L by the key (F element). Return a list of (key members) pairs, where members is a list. Groups appear in the order their key first shows up, and members keep their original order.

(groupBy even? '(1 2 3 4))            ⇒ ((#f (1 3)) (#t (2 4)))
(groupBy length '((a) (b c) (d) ()))  ⇒ ((1 ((a) (d))) (2 ((b c))) (0 (())))
(groupBy (lambda (X) X) '())          ⇒ ()
(groupBy car '((x 1) (y 2) (x 3)))    ⇒ ((x ((x 1) (x 3))) (y ((y 2))))
Show answer

A table of (key members). Append each element to its key's group, and add new keys at the end so the first-appearance order is kept.

;; add x to key k's group; a new key goes at the end
(define addTo
  (lambda (table k x)
    (cond ((null? table) (list (list k (list x))))
          ((equal? k (car (car table)))
           (cons (list k (append (cadr (car table)) (list x))) (cdr table)))
          (else (cons (car table) (addTo (cdr table) k x))))))

(define groupAll
  (lambda (F L table)
    (cond ((null? L) table)
          (else (groupAll F (cdr L) (addTo table (F (car L)) (car L)))))))

(define groupBy
  (lambda (F L)
    (groupAll F L '())))

sortedToBST

L is sorted. Write sortedToBST, which builds a balanced binary search tree in the (value left right) format:

  • the root is the element at position (quotient (length L) 2)
  • the elements before it build the left subtree, the elements after it build the right subtree, the same way.

The empty list gives the empty tree '().

(sortedToBST '())           ⇒ ()
(sortedToBST '(1))          ⇒ (1 () ())
(sortedToBST '(1 2 3))      ⇒ (2 (1 () ()) (3 () ()))
(sortedToBST '(1 2 3 4))    ⇒ (3 (2 (1 () ()) ()) (4 () ()))
(sortedToBST '(1 2 3 4 5))  ⇒ (3 (2 (1 () ()) ()) (5 (4 () ()) ()))

Not allowed: list-tail, list-ref, take or drop.

Show answer

Split at the middle position: the middle element is the root, the left half becomes the left subtree and the right half the right subtree, built the same way.

(define firstN
  (lambda (n L)
    (cond ((= n 0) '())
          (else (cons (car L) (firstN (- n 1) (cdr L)))))))

(define skipN
  (lambda (n L)
    (cond ((= n 0) L)
          (else (skipN (- n 1) (cdr L))))))

(define sortedToBST
  (lambda (L)
    (cond ((null? L) '())
          (else (let* ((m (quotient (length L) 2))
                       (after (skipN m L)))      ; starts with the root
                  (list (car after)
                        (sortedToBST (firstN m L))
                        (sortedToBST (cdr after))))))))

mergeSort

Write mergeSort, which returns the numbers in L sorted from smallest to largest, using merge sort: split the list into two halves, sort each half, then merge them. sort is off-limits.

(mergeSort '(5 2 4 1 3))     ⇒ (1 2 3 4 5)
(mergeSort '())              ⇒ ()
(mergeSort '(1))             ⇒ (1)
(mergeSort '(3 1 3))         ⇒ (1 3 3)
(mergeSort '(-1 -5 0 2 -5))  ⇒ (-5 -5 -1 0 2)

Not allowed: sort, sort!, merge, list-sort or vector-sort.

Show answer

Split in half, sort each half recursively, then merge the two sorted halves. Lists of length 0 or 1 are already sorted.

(define firstN
  (lambda (n L)
    (cond ((= n 0) '())
          (else (cons (car L) (firstN (- n 1) (cdr L)))))))

(define skipN
  (lambda (n L)
    (cond ((= n 0) L)
          (else (skipN (- n 1) (cdr L))))))

(define mergeLists
  (lambda (A B)
    (cond ((null? A) B)
          ((null? B) A)
          ((<= (car A) (car B)) (cons (car A) (mergeLists (cdr A) B)))
          (else (cons (car B) (mergeLists A (cdr B)))))))

(define mergeSort
  (lambda (L)
    (cond ((or (null? L) (null? (cdr L))) L)
          (else (let ((half (quotient (length L) 2)))
                  (mergeLists (mergeSort (firstN half L))
                              (mergeSort (skipN half L))))))))

nQueens

Write nQueens, which returns how many ways there are to place N queens on an N×N chessboard so that no two attack each other (no shared row, column or diagonal).

(nQueens 1)  ⇒ 1
(nQueens 2)  ⇒ 0
(nQueens 4)  ⇒ 2
(nQueens 5)  ⇒ 10
(nQueens 6)  ⇒ 4
Show answer

Place one queen per row. A column is safe if no earlier queen is in the same column or exactly d columns away on the row d rows up (the same diagonal). Count the ways that fill every row.

;; placed = columns of the queens already placed, most recent row first
(define safe?
  (lambda (col placed d)                 ; d = how many rows up that queen is
    (cond ((null? placed) #t)
          ((= col (car placed)) #f)                      ; same column
          ((= (abs (- col (car placed))) d) #f)          ; same diagonal
          (else (safe? col (cdr placed) (+ d 1))))))

(define tryCols                          ; count solutions trying columns col..N-1 in this row
  (lambda (N col placed)
    (cond ((= col N) 0)
          ((safe? col placed 1)
           (+ (place N (cons col placed)) (tryCols N (+ col 1) placed)))
          (else (tryCols N (+ col 1) placed)))))

(define place
  (lambda (N placed)
    (cond ((= (length placed) N) 1)      ; every row has a queen
          (else (tryCols N 0 placed)))))

(define nQueens
  (lambda (N)
    (place N '())))

determinant

Matrices are lists of rows, and M is square. Write determinant, using cofactor expansion along the first row: det M = Σ (−1)ʲ · m₀ⱼ · det(minor₀ⱼ), where minor₀ⱼ is M with row 0 and column j removed.

(determinant '((5)))                       ⇒ 5
(determinant '((1 2) (3 4)))               ⇒ -2
(determinant '((6 1 1) (4 -2 5) (2 8 7)))  ⇒ -306
(determinant '((1 0 0) (0 1 0) (0 0 1)))   ⇒ 1
(determinant '((1 2) (2 4)))               ⇒ 0

Not allowed: matrix-determinant or apply.

Show answer

Cofactor expansion: for each column j of the first row, multiply its entry by the determinant of the minor, with signs alternating + − + …. A 1×1 matrix is its own determinant.

(define removeAt                         ; L without position j
  (lambda (j L)
    (cond ((= j 0) (cdr L))
          (else (cons (car L) (removeAt (- j 1) (cdr L)))))))

(define minor                            ; drop row 0 and column j
  (lambda (M j)
    (map (lambda (row) (removeAt j row)) (cdr M))))

(define expand                           ; sum of the terms for columns j, j+1, ...
  (lambda (M row0 j sign)
    (cond ((null? row0) 0)
          (else (+ (* sign (car row0) (determinant (minor M j)))
                   (expand M (cdr row0) (+ j 1) (- sign)))))))

(define determinant
  (lambda (M)
    (cond ((null? (cdr M)) (car (car M)))     ; 1x1
          (else (expand M (car M) 0 1)))))

allBalanced

Brackets are written as the symbols o (open) and c (close). Write allBalanced, which returns every balanced sequence that uses exactly N pairs, as lists. The order of the sequences doesn't matter.

(allBalanced 0)  ⇒ (())
(allBalanced 1)  ⇒ ((o c))
(allBalanced 2)  ⇒ ((o o c c) (o c o c))
(allBalanced 3)  ⇒ ((o o o c c c) (o o c o c c) (o o c c o c) (o c o o c c) (o c o c o c))

The results can come in any order.

Show answer

Build left to right, tracking how many opens and closes are still to use. You can open while any opens remain, but only close when more closes than opens remain (there's an open bracket to close).

;; opens/closes = how many of each are still to be used
(define build
  (lambda (opens closes)
    (cond ((and (= opens 0) (= closes 0)) (list '()))
          (else (append
                 (if (> opens 0)                 ; can always open if any are left
                     (map (lambda (s) (cons 'o s)) (build (- opens 1) closes))
                     '())
                 (if (> closes opens)            ; can only close an open bracket
                     (map (lambda (s) (cons 'c s)) (build opens (- closes 1)))
                     '()))))))

(define allBalanced
  (lambda (N)
    (build N N)))

uniquePerms

L may contain repeated elements. Write uniquePerms, which returns every different ordering of L, each exactly once. The order of the orderings doesn't matter.

(uniquePerms '(a a b))  ⇒ ((a a b) (a b a) (b a a))
(uniquePerms '(1 1))    ⇒ ((1 1))
(uniquePerms '())       ⇒ (())
(uniquePerms '(x y))    ⇒ ((x y) (y x))

The results can come in any order. Not allowed: permutations or remove-duplicates.

Show answer

Like permutations, but only try each DIFFERENT value in front. Two equal elements then never start the same ordering twice.

(define removeOne
  (lambda (x L)
    (cond ((null? L) '())
          ((equal? x (car L)) (cdr L))
          (else (cons (car L) (removeOne x (cdr L)))))))

(define distinct                         ; each different element once
  (lambda (L)
    (cond ((null? L) '())
          (else (cons (car L)
                      (distinct (filter (lambda (y) (not (equal? y (car L)))) (cdr L))))))))

;; only try each DIFFERENT value in front, so no ordering is built twice
(define uniquePerms
  (lambda (L)
    (cond ((null? L) (list '()))
          (else (apply append
                       (map (lambda (x)
                              (map (lambda (p) (cons x p))
                                   (uniquePerms (removeOne x L))))
                            (distinct L)))))))

subsetsSumTo

L is a list of different positive numbers. Write subsetsSumTo, which returns every subset of L whose elements add up to N. Each subset keeps the elements in the same order as L; the order of the subsets doesn't matter.

(subsetsSumTo 5 '(1 2 3 4))  ⇒ ((1 4) (2 3))
(subsetsSumTo 3 '(1 2 3))    ⇒ ((1 2) (3))
(subsetsSumTo 0 '(1 2))      ⇒ (())
(subsetsSumTo 10 '(1 2))     ⇒ ()

The results can come in any order.

Show answer

countSubsetsSum that builds the subsets instead of counting them: "use it" conses the number onto the solutions for the smaller target.

(define subsetsSumTo
  (lambda (N L)
    (cond ((= N 0) (list '()))           ; all positive, so only the empty subset
          ((or (< N 0) (null? L)) '())
          (else (append (map (lambda (s) (cons (car L) s))       ; use (car L)
                             (subsetsSumTo (- N (car L)) (cdr L)))
                        (subsetsSumTo N (cdr L)))))))             ; skip it

evalInfix

E is a flat infix expression: numbers separated by the symbols + - * /, like (1 + 2 * 3). A sub-list counts as a bracketed expression. Write evalInfix, which evaluates it with normal precedence: * and / first, then + and -, each left to right. All divisions in the tests come out whole.

(evalInfix '(1 + 2 * 3))      ⇒ 7
(evalInfix '(10 - 4 - 3))     ⇒ 3
(evalInfix '(2 * 3 + 4 * 5))  ⇒ 26
(evalInfix '(7))              ⇒ 7
(evalInfix '(8 / 4 / 2))      ⇒ 1
(evalInfix '((1 + 2) * 3))    ⇒ 9

Not allowed: eval.

Show answer

Two passes give the precedence. termLoop swallows runs of * and /; exprLoop then adds and subtracts the finished terms, left to right. Sub-lists are evaluated recursively as brackets.

(define item                             ; a number, or a bracketed sub-expression
  (lambda (x)
    (if (list? x) (evalInfix x) x)))

;; keep multiplying/dividing while the next operator is * or /
;; returns (value rest-of-list)
(define termLoop
  (lambda (acc L)
    (cond ((and (not (null? L)) (equal? (car L) '*))
           (termLoop (* acc (item (cadr L))) (cddr L)))
          ((and (not (null? L)) (equal? (car L) '/))
           (termLoop (/ acc (item (cadr L))) (cddr L)))
          (else (list acc L)))))

;; then add/subtract whole terms, left to right
(define exprLoop
  (lambda (acc L)
    (cond ((null? L) acc)
          (else (let ((t (termLoop (item (cadr L)) (cddr L))))
                  (exprLoop (if (equal? (car L) '+) (+ acc (car t)) (- acc (car t)))
                            (cadr t)))))))

(define evalInfix
  (lambda (E)
    (let ((t (termLoop (item (car E)) (cdr E))))
      (exprLoop (car t) (cadr t)))))

polyMultiply

A polynomial is a list of coefficients, lowest power first: (2 0 3) means 2 + 0x + 3x². Write polyMultiply, which returns the product of P and Q in the same format. Neither list is empty.

(polyMultiply '(1 1) '(1 1))    ⇒ (1 2 1)
(polyMultiply '(1 2) '(3))      ⇒ (3 6)
(polyMultiply '(0 1) '(0 1))    ⇒ (0 0 1)
(polyMultiply '(1 -1) '(1 1))   ⇒ (1 0 -1)
(polyMultiply '(2 0 3) '(1 4))  ⇒ (2 8 3 12)
Show answer

(p₀ + x·rest) × Q = p₀·Q + x·(rest × Q). Multiplying by x shifts the coefficients up one place, which is just cons 0 on the front.

(define polyAdd
  (lambda (P Q)
    (cond ((null? P) Q)
          ((null? Q) P)
          (else (cons (+ (car P) (car Q)) (polyAdd (cdr P) (cdr Q)))))))

(define scale
  (lambda (k Q)
    (map (lambda (c) (* k c)) Q)))

;; (p0 + x*rest) * Q = p0*Q + x*(rest*Q); "times x" = cons a 0 on the front
(define polyMultiply
  (lambda (P Q)
    (cond ((null? (cdr P)) (scale (car P) Q))
          (else (polyAdd (scale (car P) Q)
                         (cons 0 (polyMultiply (cdr P) Q)))))))

lisLength

Write lisLength, which returns the length of the longest strictly increasing subsequence of L (the elements you keep don't have to be next to each other, but they must keep their order).

(lisLength '(3 1 4 1 5 9 2 6))  ⇒ 4
(lisLength '())                 ⇒ 0
(lisLength '(5 4 3))            ⇒ 1
(lisLength '(1 2 3))            ⇒ 3
(lisLength '(2 2 2))            ⇒ 1

Not allowed: sort.

Show answer

Carry the last value you kept. Each element can be skipped, or used if it's bigger than that value. Take whichever choice gives the longer subsequence.

;; longest increasing subsequence of L using only values bigger than prev
;; (prev is #f at the start, meaning "no limit")
(define lis
  (lambda (L prev)
    (cond ((null? L) 0)
          ((and prev (<= (car L) prev)) (lis (cdr L) prev))   ; can't use it
          (else (max (+ 1 (lis (cdr L) (car L)))               ; use it
                     (lis (cdr L) prev))))))                   ; skip it

(define lisLength
  (lambda (L)
    (lis L #f)))

editDistance

Write editDistance, which returns the fewest single-element edits (insert one, delete one, or replace one) needed to turn list A into list B.

(editDistance '(c a t) '(c u t s))  ⇒ 2
(editDistance '() '(a b))           ⇒ 2
(editDistance '(a b c) '(a b c))    ⇒ 0
(editDistance '(a b) '(b a))        ⇒ 2
(editDistance '(x) '())             ⇒ 1
Show answer

If the fronts match, they cost nothing. Otherwise it costs 1 plus the cheapest of delete (drop from A), insert (drop from B) or replace (drop both).

(define editDistance
  (lambda (A B)
    (cond ((null? A) (length B))         ; insert the rest of B
          ((null? B) (length A))         ; delete the rest of A
          ((equal? (car A) (car B)) (editDistance (cdr A) (cdr B)))
          (else (+ 1 (min (editDistance (cdr A) B)           ; delete
                          (editDistance A (cdr B))           ; insert
                          (editDistance (cdr A) (cdr B)))))))) ; replace

knapsack

Each item is a list (weight value). Write knapsack, which returns the largest total value you can carry without the total weight going over CAP. Each item can be taken at most once.

(knapsack 5 '((2 3) (3 4) (4 5) (5 6)))  ⇒ 7
(knapsack 7 '((1 1) (3 4) (4 5) (5 7)))  ⇒ 9
(knapsack 0 '((1 1)))                    ⇒ 0
(knapsack 10 '())                        ⇒ 0
(knapsack 4 '((5 10)))                   ⇒ 0
Show answer

For each item: if it's too heavy, skip it. Otherwise take the better of "take it" (its value + the best with less capacity) and "leave it".

(define knapsack
  (lambda (CAP items)
    (cond ((null? items) 0)
          (else (let ((w (car (car items)))
                      (v (cadr (car items))))
                  (if (> w CAP)
                      (knapsack CAP (cdr items))                       ; too heavy
                      (max (+ v (knapsack (- CAP w) (cdr items)))       ; take it
                           (knapsack CAP (cdr items)))))))))           ; leave it

coinCombos

Write coinCombos, which returns every way to make N from the coin values in COINS (each coin can be used any number of times). Each way lists its coins in the same order as COINS; the order of the ways doesn't matter.

(coinCombos 4 '(1 2))    ⇒ ((1 1 1 1) (1 1 2) (2 2))
(coinCombos 5 '(1 2 5))  ⇒ ((1 1 1 1 1) (1 1 1 2) (1 2 2) (5))
(coinCombos 0 '(1 2))    ⇒ (())
(coinCombos 3 '(2))      ⇒ ()

The results can come in any order.

Show answer

countChange that builds the lists instead of counting. Using the first coin repeatedly keeps each way in the same order as COINS.

;; countChange, but building the ways instead of counting them
(define coinCombos
  (lambda (N COINS)
    (cond ((= N 0) (list '()))
          ((or (< N 0) (null? COINS)) '())
          (else (append (map (lambda (w) (cons (car COINS) w))
                             (coinCombos (- N (car COINS)) COINS))   ; use the first coin again
                        (coinCombos N (cdr COINS)))))))              ; never use it

countIslands

GRID is a list of rows of 0s and 1s. An island is a group of 1s connected up, down, left or right (not diagonally). Write countIslands, which returns how many islands there are.

(countIslands '((1 1 0) (0 1 0) (0 0 1)))  ⇒ 2
(countIslands '((0 0) (0 0)))              ⇒ 0
(countIslands '((1)))                      ⇒ 1
(countIslands '((1 0 1) (0 1 0) (1 0 1)))  ⇒ 5
(countIslands '())                         ⇒ 0
Show answer

Collect the coordinates of every land cell. Repeatedly take one cell, flood-remove everything connected to it, and count one island each time.

;; Turn the grid into a list of land cells (row col), then repeatedly
;; take one cell, wash away everything connected to it, and count.

(define rowCells                         ; land cells in one row
  (lambda (row r c)
    (cond ((null? row) '())
          ((= (car row) 1) (cons (list r c) (rowCells (cdr row) r (+ c 1))))
          (else (rowCells (cdr row) r (+ c 1))))))

(define landCells
  (lambda (grid r)
    (cond ((null? grid) '())
          (else (append (rowCells (car grid) r 0) (landCells (cdr grid) (+ r 1)))))))

(define neighbours
  (lambda (p)
    (let ((r (car p)) (c (cadr p)))
      (list (list (- r 1) c) (list (+ r 1) c) (list r (- c 1)) (list r (+ c 1))))))

(define flood                            ; remove every cell reachable from frontier
  (lambda (frontier cells)
    (cond ((null? frontier) cells)
          (else (let ((found (filter (lambda (q) (member q cells))
                                     (neighbours (car frontier)))))
                  (flood (append (cdr frontier) found)
                         (filter (lambda (q) (not (member q found))) cells)))))))

(define countFrom
  (lambda (cells)
    (cond ((null? cells) 0)
          (else (+ 1 (countFrom (flood (list (car cells)) (cdr cells))))))))

(define countIslands
  (lambda (GRID)
    (countFrom (landCells GRID 0))))

rotateMatrix

Matrices are lists of rows. Write rotateMatrix, which returns M rotated 90° clockwise. M has at least one row and one column, but needn't be square.

(rotateMatrix '((1 2) (3 4)))              ⇒ ((3 1) (4 2))
(rotateMatrix '((1 2 3) (4 5 6)))          ⇒ ((4 1) (5 2) (6 3))
(rotateMatrix '((1)))                      ⇒ ((1))
(rotateMatrix '((1 2 3) (4 5 6) (7 8 9)))  ⇒ ((7 4 1) (8 5 2) (9 6 3))

Not allowed: apply.

Show answer

Rotating clockwise = flip the rows upside down (reverse), then transpose.

(define transpose
  (lambda (M)
    (cond ((null? (car M)) '())
          (else (cons (map car M) (transpose (map cdr M)))))))

;; clockwise = flip the rows upside down, then transpose
(define rotateMatrix
  (lambda (M)
    (transpose (reverse M))))

spiralOrder

Write spiralOrder, which returns the elements of matrix M in clockwise spiral order, starting at the top-left. An empty matrix gives '().

(spiralOrder '((1 2 3) (4 5 6) (7 8 9)))  ⇒ (1 2 3 6 9 8 7 4 5)
(spiralOrder '((1 2) (3 4)))              ⇒ (1 2 4 3)
(spiralOrder '((1 2 3 4)))                ⇒ (1 2 3 4)
(spiralOrder '((1) (2) (3)))              ⇒ (1 2 3)
(spiralOrder '())                         ⇒ ()

Not allowed: apply.

Show answer

Read the top row, then rotate what's left ANTI-clockwise (transpose, then reverse) so the next edge becomes the top row. Repeat until nothing is left.

(define transpose
  (lambda (M)
    (cond ((null? (car M)) '())
          (else (cons (map car M) (transpose (map cdr M)))))))

;; take the top row, then turn what's left anticlockwise so the
;; next edge to read becomes the new top row
(define spiralOrder
  (lambda (M)
    (cond ((null? M) '())
          ((null? (cdr M)) (car M))
          (else (append (car M)
                        (spiralOrder (reverse (transpose (cdr M)))))))))

bstDelete

Trees use the same format as bstInsert: '() (empty) or a list (value left right). T is a binary search tree. Write bstDelete, which returns T with N removed. If the node has two children, replace its value with the smallest value in its right subtree and delete that value from the right subtree. If N isn't there, return T unchanged.

(bstDelete 3 '(5 (3 () ()) (8 () ())))                ⇒ (5 () (8 () ()))
(bstDelete 8 '(5 (3 () ()) (8 () (9 () ()))))         ⇒ (5 (3 () ()) (9 () ()))
(bstDelete 5 '(5 (3 () ()) (8 (7 () ()) (9 () ()))))  ⇒ (7 (3 () ()) (8 () (9 () ())))
(bstDelete 4 '(5 () ()))                              ⇒ (5 () ())
(bstDelete 5 '())                                     ⇒ ()
Show answer

Search left or right as in bstContains. A node with at most one child is replaced by that child. With two children, copy in the smallest value from the right subtree and delete that value from the right.

(define bstMin
  (lambda (T)
    (if (null? (cadr T)) (car T) (bstMin (cadr T)))))

(define bstDelete
  (lambda (N T)
    (cond ((null? T) '())
          ((< N (car T)) (list (car T) (bstDelete N (cadr T)) (caddr T)))
          ((> N (car T)) (list (car T) (cadr T) (bstDelete N (caddr T))))
          ((null? (cadr T)) (caddr T))       ; found it, no left child
          ((null? (caddr T)) (cadr T))       ; found it, no right child
          (else (let ((m (bstMin (caddr T))))
                  (list m (cadr T) (bstDelete m (caddr T))))))))

isBalanced

Trees use the same format as bstInsert: '() (empty) or a list (value left right). A tree is balanced if, at EVERY node, the heights of the left and right subtrees differ by at most 1. Write isBalanced.

(isBalanced '())
  ⇒ #t
(isBalanced '(1 () ()))
  ⇒ #t
(isBalanced '(1 (2 (3 () ()) ()) ()))
  ⇒ #f
(isBalanced '(1 (2 (4 () ()) ()) (3 () ())))
  ⇒ #t
(isBalanced '(1 (2 (4 (5 () ()) ()) ()) (3 (6 () ()) (7 () ()))))
  ⇒ #f
Show answer

At every node, the two subtree heights must differ by at most 1, AND both subtrees must themselves be balanced.

(define height
  (lambda (T)
    (if (null? T) 0 (+ 1 (max (height (cadr T)) (height (caddr T)))))))

(define isBalanced
  (lambda (T)
    (cond ((null? T) #t)
          (else (and (<= (abs (- (height (cadr T)) (height (caddr T)))) 1)
                     (isBalanced (cadr T))
                     (isBalanced (caddr T)))))))

lcsList

Write lcsList, which returns the longest common subsequence of lists A and B: the longest list whose elements appear, in order, in both (not necessarily next to each other). The tests only use inputs with a single longest answer.

(lcsList '(a b c d) '(a c d))    ⇒ (a c d)
(lcsList '(x y) '(a b))          ⇒ ()
(lcsList '(1 2 3) '(1 2 3))      ⇒ (1 2 3)
(lcsList '(a x b y c) '(a b c))  ⇒ (a b c)
(lcsList '(k a t e) '(c a t))    ⇒ (a t)
Show answer

Same recursion as lcsLength, but build the actual list: cons the matching fronts, otherwise keep the longer of the two options.

(define lcsList
  (lambda (A B)
    (cond ((or (null? A) (null? B)) '())
          ((equal? (car A) (car B)) (cons (car A) (lcsList (cdr A) (cdr B))))
          (else (let ((x (lcsList (cdr A) B))
                      (y (lcsList A (cdr B))))
                  (if (>= (length x) (length y)) x y))))))

partitionsList

Write partitionsList, which returns every partition of N ≥ 0 as a list of parts from largest to smallest (so 3+1 is (3 1)). The order of the partitions doesn't matter.

(partitionsList 4)  ⇒ ((4) (3 1) (2 2) (2 1 1) (1 1 1 1))
(partitionsList 1)  ⇒ ((1))
(partitionsList 0)  ⇒ (())
(partitionsList 3)  ⇒ ((3) (2 1) (1 1 1))

The results can come in any order.

Show answer

Build partitions with parts at most k, largest first: either use k (and build the rest with parts at most k) or move down to k−1.

;; partitions of n whose parts are all <= k (largest first)
(define partsUpTo
  (lambda (n k)
    (cond ((= n 0) (list '()))
          ((= k 0) '())
          (else (append (if (<= k n)
                            (map (lambda (p) (cons k p)) (partsUpTo (- n k) k))   ; use a k
                            '())
                        (partsUpTo n (- k 1)))))))                               ; no k at all

(define partitionsList
  (lambda (N)
    (partsUpTo N N)))

nextPermutation

Write nextPermutation, which returns the next arrangement of the numbers in L in dictionary order. If L is already the last arrangement (largest first), wrap around to the first (smallest first).

(nextPermutation '(1 2 3))  ⇒ (1 3 2)
(nextPermutation '(1 3 2))  ⇒ (2 1 3)
(nextPermutation '(3 2 1))  ⇒ (1 2 3)
(nextPermutation '(1 1 5))  ⇒ (1 5 1)
(nextPermutation '(2 3 1))  ⇒ (3 1 2)
Show answer

Find the shortest tail that can still be rearranged upward. Swap its first element with the smallest bigger element after it, then put the rest in ascending order. If the whole list is descending, wrap round to ascending.

(define nonIncreasing                    ; already the last arrangement?
  (lambda (L)
    (or (null? L) (null? (cdr L))
        (and (>= (car L) (cadr L)) (nonIncreasing (cdr L))))))

(define lastBigger                       ; last element of L bigger than x
  (lambda (x L)
    (cond ((null? L) #f)
          (else (let ((later (lastBigger x (cdr L))))
                  (cond (later later)
                        ((> (car L) x) (car L))
                        (else #f)))))))

(define replaceFirst
  (lambda (old new L)
    (cond ((equal? (car L) old) (cons new (cdr L)))
          (else (cons (car L) (replaceFirst old new (cdr L)))))))

(define nextP
  (lambda (L)
    (cond ((not (nonIncreasing (cdr L)))     ; the rest can still move on
           (cons (car L) (nextP (cdr L))))
          (else                              ; the rest is maxed out: bump (car L)
           (let* ((pivot (car L))
                  (up (lastBigger pivot (cdr L)))
                  ;; swap pivot into up's last position, then put the rest smallest-first
                  (rest (reverse (replaceFirst up pivot (reverse (cdr L))))))
             (cons up (reverse rest)))))))

(define nextPermutation
  (lambda (L)
    (if (nonIncreasing L)
        (reverse L)                          ; wrap round to the first arrangement
        (nextP L))))

Q3 exam practice

sumWith

sumWith takes any number of numbers and returns a function. That function also takes any number of numbers, and returns the total of everything: the numbers given to sumWith and the numbers given to the new function.

((sumWith 1 2) 3 4) → 10

Both levels take any number of arguments, so you need two (lambda name …) forms with no brackets around the name.

((sumWith 1 2) 3 4)
  ⇒ 10
((sumWith) 5)
  ⇒ 5
((sumWith 10))
  ⇒ 10
((sumWith))
  ⇒ 0
(let ((add100 (sumWith 50 50))) (list (add100 1) (add100 2 3)))
  ⇒ (101 105)
(map (sumWith 1 1) '(1 2 3))
  ⇒ (3 4 5)

Not allowed: foldl or foldr.

Show answer

Two variable-arity lambdas. The outer one remembers its numbers; the inner one adds both batches with apply +.

(define sumWith
  (lambda xs                             ; first batch of numbers
    (lambda ys                           ; second batch
      (+ (apply + xs) (apply + ys)))))

zipApply

zipApply takes any number of one-argument functions and returns a function. That function takes the same number of values and calls each function on the value in the same position. It returns the list of results:

((zipApply car cdr length) '(1 2) '(3 4) '(5 6 7)) → (1 (4) 3)

The first function goes with the first value, the second with the second, and so on.

((zipApply car cdr length) '(1 2) '(3 4) '(5 6 7))
  ⇒ (1 (4) 3)
((zipApply sqrt -) 16 5)
  ⇒ (4 -5)
((zipApply))
  ⇒ ()
((zipApply list) 'a)
  ⇒ ((a))
(let ((both (zipApply even? odd?))) (list (both 2 2) (both 3 3)))
  ⇒ ((#t #f) (#f #t))
Show answer

map can walk two lists at once: the list of functions and the list of values, calling each function on its matching value.

(define zipApply
  (lambda fns
    (lambda vals
      (map (lambda (f v) (f v)) fns vals))))   ; map can walk two lists together

repeated

repeated takes a one-argument function f and a whole number n ≥ 0. It returns a new function that applies f to its argument **n times**:

((repeated f 3) x) means (f (f (f x))).

(repeated f 0) returns a function that gives back its argument unchanged.

Solve it by recursion on n: each step builds a new closure out of a smaller one.

((repeated (lambda (x) (* x 2)) 3) 1)               ⇒ 8
((repeated cdr 2) '(a b c d))                       ⇒ (c d)
((repeated sqrt 0) 81)                              ⇒ 81
((repeated list 3) 'x)                              ⇒ (((x)))
(map (repeated (lambda (x) (+ x 1)) 5) '(0 10))     ⇒ (5 15)
((repeated (repeated (lambda (x) (* x 2)) 2) 3) 1)  ⇒ 64
Show answer

Recursion that builds closures: f applied 0 times is the identity function. Otherwise wrap one more call of f around the function for n−1.

(define repeated
  (lambda (f n)
    (cond ((= n 0) (lambda (x) x))                  ; apply f zero times
          (else (let ((g (repeated f (- n 1))))     ; f applied n-1 times
                  (lambda (x) (f (g x))))))))

keepAll

keepAll takes any number of predicates (tests that return #t or #f) and returns a function. That function takes a list L and keeps only the elements that pass every predicate, in their original order:

((keepAll even? positive?) '(-2 3 4 6 7)) → (4 6)

Check the predicates in order, and stop at the first one that fails. With no predicates, nothing is removed.

((keepAll even? positive?) '(-2 3 4 6 7))
  ⇒ (4 6)
((keepAll) '(a b c))
  ⇒ (a b c)
((keepAll number?) '())
  ⇒ ()
((keepAll number? (lambda (x) (> x 10)) odd?) '(11 12 x 13 5))
  ⇒ (11 13)
(let ((smallEvens (keepAll even? (lambda (x) (< x 5))))) (list (smallEvens '(1 2 3 4 5 6)) (smallEvens '(8 0))))
  ⇒ ((2 4) (0))
Show answer

filter with a combined test: an element is kept only if it passes every predicate. The passesAll helper stops at the first predicate that fails.

;; does x pass every test in preds? stops at the first failure
(define passesAll
  (lambda (preds x)
    (cond ((null? preds) #t)
          (((car preds) x) (passesAll (cdr preds) x))
          (else #f))))

(define keepAll
  (lambda preds
    (lambda (L)
      (filter (lambda (x) (passesAll preds x)) L))))

curryN

Currying means taking arguments one at a time. curryN takes a function f and a whole number n ≥ 1, and returns a one-argument function. Each call takes the next argument and returns another one-argument function, until n arguments have been collected. Then f is called with all of them, in order:

((((curryN list 3) 'a) 'b) 'c) → (a b c)
(((curryN - 2) 10) 3) → 7

The arguments collected so far have to be remembered between calls. That's the closure's job.

((((curryN list 3) 'a) 'b) 'c)
  ⇒ (a b c)
(((curryN - 2) 10) 3)
  ⇒ 7
((curryN sqrt 1) 49)
  ⇒ 7
(let ((add5 ((curryN + 2) 5))) (list (add5 1) (add5 10)))
  ⇒ (6 15)
(map ((curryN cons 2) 'x) '(() (y)))
  ⇒ ((x) (x y))
(((((curryN max 4) 3) 9) 2) 7)
  ⇒ 9
Show answer

Collect the arguments one call at a time in a list carried inside each closure. When the last one arrives, apply f to them in the right order.

;; collected holds the arguments so far, newest first
(define collect
  (lambda (f n collected)
    (lambda (x)
      (cond ((= n 1) (apply f (reverse (cons x collected))))   ; last one: call f
            (else (collect f (- n 1) (cons x collected)))))))

(define curryN
  (lambda (f n)
    (collect f n '())))

lookupFn

lookupFn takes any number of key–value pairs, written flat: key, value, key, value… It returns a function of one key. That function gives back the value paired with that key, or #f if the key isn't there. If a key appears twice, the first one wins.

(define colour (lookupFn 'sky 'blue 'grass 'green))
(colour 'grass) ; green
(colour 'sun)   ; #f

The arguments come in twos, so you'll step through them two at a time (cddr, like in chain).

((lookupFn 'sky 'blue 'grass 'green) 'grass)  ⇒ green
((lookupFn 'sky 'blue 'grass 'green) 'sun)    ⇒ #f
((lookupFn) 'x)                               ⇒ #f
((lookupFn 'a 1 'b 2 'a 3) 'a)                ⇒ 1
((lookupFn 'a 'b 'b 'c) 'b)                   ⇒ c
((lookupFn 1 'one 2 'two) 2)                  ⇒ two
(map (lookupFn 'x 10 'y 20) '(y x z))         ⇒ (20 10 #f)
Show answer

The pairs are flat: key, value, key, value. Step through them two at a time with cddr, returning the value right after the first matching key.

;; L is (key value key value ...)
(define findValue
  (lambda (k L)
    (cond ((null? L) #f)
          ((equal? k (car L)) (cadr L))
          (else (findValue k (cddr L))))))   ; skip a key AND its value

(define lookupFn
  (lambda pairs
    (lambda (k)
      (findValue k pairs))))

bestBy

bestBy takes a one-argument function f that turns things into numbers. It returns a function that takes one or more arguments and returns the argument with the biggest f value. If there's a tie, the earliest one wins.

((bestBy length) '(a) '(b c d) '(e f)) → (b c d)
((bestBy abs) 3 -7 5) → -7

It returns the argument itself, not its f value.

((bestBy length) '(a) '(b c d) '(e f))
  ⇒ (b c d)
((bestBy abs) 3 -7 5)
  ⇒ -7
((bestBy abs) 4)
  ⇒ 4
((bestBy abs) 2 -5 5)
  ⇒ -5
((bestBy car) '(1 a) '(3 b) '(3 c) '(2 d))
  ⇒ (3 b)
((bestBy (lambda (x) (- x))) 4 1 9)
  ⇒ 1
(let ((longest (bestBy length))) (list (longest '(1) '(1 2)) (longest '() '(x))))
  ⇒ ((1 2) (x))

Not allowed: argmax or argmin.

Show answer

Best-so-far with a score function. Replace only on a STRICTLY higher score so ties keep the earliest, and return the argument itself, not its score.

;; best is the winner so far; only replace it if something is strictly bigger
(define bestOf
  (lambda (f best L)
    (cond ((null? L) best)
          ((> (f (car L)) (f best)) (bestOf f (car L) (cdr L)))
          (else (bestOf f best (cdr L))))))

(define bestBy
  (lambda (f)
    (lambda args
      (bestOf f (car args) (cdr args)))))

startWith

This is the mock's chain, turned inside out. startWith takes a value x and returns a function that takes any number of one-argument functions. It chains them on x exactly like chain: the last function is called on x first, then the one before it on that result, and so on back to the first.

((startWith 25) list (lambda (x) (+ x 2)) sqrt) → (7)

With no functions at all, you get x back.

((startWith 25) list (lambda (x) (+ x 2)) sqrt)
  ⇒ (7)
((startWith 625) sqrt sqrt)
  ⇒ 5
((startWith 'hugs) list list)
  ⇒ ((hugs))
((startWith 9))
  ⇒ 9
((startWith '(1 2 3)) car cdr)
  ⇒ 2
(let ((from10 (startWith 10))) (list (from10 -) (from10 list -)))
  ⇒ (-10 (-10))
Show answer

chain inside out: remember x, and apply the functions right to left. No functions means x comes back unchanged.

;; apply the functions right to left
(define chainOn
  (lambda (fns x)
    (cond ((null? fns) x)
          (else ((car fns) (chainOn (cdr fns) x))))))

(define startWith
  (lambda (x)
    (lambda fns
      (chainOn fns x))))

withCount

withCount takes a function f (with any number of arguments) and returns a new function that behaves **exactly like f**, but also counts how many times it has been used:

  • Called with one or more arguments, it calls f on them, adds 1 to its count, and returns f's result.
  • Called with no arguments, it returns how many times it has been used so far. Asking for the count doesn't count as a use.
(define plus (withCount +))
(plus 1 2)   ; 3
(plus 4 5 6) ; 15
(plus)       ; 2

Two functions made by withCount keep separate counts. You need set! (see makeCounter in Scope & Closures).

(let ((plus (withCount +))) (plus 1 2))
  ⇒ 3
(let ((plus (withCount +))) (plus 1 2) (plus 4 5 6) (plus))
  ⇒ 2
((withCount +))
  ⇒ 0
(let* ((s (withCount sqrt)) (a (s 16)) (b (s 81))) (list a b (s)))
  ⇒ (4 9 2)
(let ((m (withCount max))) (m 1 2) (m) (m))
  ⇒ 1
(let ((a (withCount list)) (b (withCount list))) (a 1) (a 2) (b 3) (list (a) (b)))
  ⇒ (2 1)
Show answer

A private counter in a let, separate for every function made. Calls with arguments bump it and pass the call through with apply; a call with none reports the count.

(define withCount
  (lambda (f)
    (let ((count 0))                     ; each new function gets its own count
      (lambda args
        (cond ((null? args) count)       ; no arguments: just report
              (else (set! count (+ count 1))
                    (apply f args)))))))

chainMany

The mock's chain, as a closure, with one twist. chainMany takes one or more functions and returns a function that takes any number of arguments. When that function is called:

  • the last function fn is called on all the arguments;
  • then the functions before it are applied one at a time, right to left, like chain.

((chainMany list +) 1 2 3) → (6): first (+ 1 2 3) is 6, then (list 6).
((chainMany sqrt sqrt +) 600 25) → 5

Only the last function gets several arguments. Every other function gets exactly one.

((chainMany list +) 1 2 3)
  ⇒ (6)
((chainMany sqrt sqrt +) 600 25)
  ⇒ 5
((chainMany +) 1 2 3 4)
  ⇒ 10
((chainMany length list))
  ⇒ 0
((chainMany car reverse list) 'a 'b 'c)
  ⇒ c
((chainMany (lambda (x) (* x 10)) -) 3 1)
  ⇒ 20
(map (chainMany list -) '(5 6))
  ⇒ ((-5) (-6))
(let ((f (chainMany length append))) (list (f '(1 2) '(3)) (f '(a) '(b) '(c d))))
  ⇒ (3 4)
Show answer

Only the LAST function gets all the arguments, using apply. Then each earlier function is applied to the result, one at a time, right to left.

(define runChain
  (lambda (fns args)
    (cond ((null? (cdr fns)) (apply (car fns) args))     ; last function gets all args
          (else ((car fns) (runChain (cdr fns) args))))))

(define chainMany
  (lambda fns
    (lambda args
      (runChain fns args))))

The house

Every problem in this section starts with these definitions loaded.

(define Library (list 'library 'book 'chair))
(define Dungeon (list 'dungeon 'skeleton Library))
(define Cellar (list 'cellar 'treasure 'rats Dungeon))
(define Fridge (list 'fridge 'sausages 'unidentified_head))
(define Kitchen (list 'kitchen Cellar Fridge))
(define DiningRoom (list 'diningRoom 'table Library Kitchen))
(define Bathroom (list 'bathroom 'toilet 'bath 'ghost Dungeon))
(define Bedroom (list 'bedroom 'bed Bathroom))
(define Hall (list 'hall DiningRoom Kitchen Bedroom 'suit_of_armour))
(define House (list 'house Hall))

(define Shed (list 'shed 'spade 'rats))
(define Garden (list 'garden 'spade Shed 'pond))
(define Cottage (list 'cottage 'rats Garden 'lamp))

contents

R is a single room, not the whole house. Write contents, which returns the objects in R: every element after the room's name that is not a list. Sub-rooms are left out.

(contents Hall)        ⇒ (suit_of_armour)
(contents Cellar)      ⇒ (treasure rats)
(contents Kitchen)     ⇒ ()
(contents Library)     ⇒ (book chair)
(contents DiningRoom)  ⇒ (table)

Not allowed: filter, filter-not, filter-map or remf.

Show answer

Skip the room's name with cdr, then keep only the elements that aren't lists. Lists are sub-rooms, not objects.

(define keepAtoms                        ; the elements of L that aren't lists
  (lambda (L)
    (cond ((null? L) '())
          ((list? (car L)) (keepAtoms (cdr L)))       ; a room: skip it
          (else (cons (car L) (keepAtoms (cdr L)))))))

(define contents
  (lambda (R)
    (keepAtoms (cdr R))))                ; skip the room's name

subRooms

Write subRooms, which returns the names of the rooms directly inside the room R, in order. Don't look any deeper than one level.

(subRooms Hall)        ⇒ (diningRoom kitchen bedroom)
(subRooms Library)     ⇒ ()
(subRooms Cellar)      ⇒ (dungeon)
(subRooms DiningRoom)  ⇒ (library kitchen)
(subRooms House)       ⇒ (hall)

Not allowed: filter, filter-map or map.

Show answer

The opposite filter: keep only the elements that ARE lists, and take each one's name, (car room).

(define roomNames                        ; names of the rooms in L
  (lambda (L)
    (cond ((null? L) '())
          ((list? (car L)) (cons (car (car L)) (roomNames (cdr L))))
          (else (roomNames (cdr L))))))

(define subRooms
  (lambda (R)
    (roomNames (cdr R))))

countObjects

Write countObjects, which counts every object in the room T and in every room inside it, at any depth. Room names don't count. If a room can be reached along several paths, count its objects once per path: just count what's in the structure.

(countObjects Library)  ⇒ 2
(countObjects Dungeon)  ⇒ 3
(countObjects Fridge)   ⇒ 2
(countObjects Kitchen)  ⇒ 7
(countObjects Cottage)  ⇒ 6
(countObjects House)    ⇒ 25

Not allowed: flatten or count.

Show answer

Skip the room's name. Each object counts 1 and each sub-room counts all of ITS objects, which is a recursive call.

(define countIn                          ; objects in a list of things
  (lambda (L)
    (cond ((null? L) 0)
          ((list? (car L)) (+ (countObjects (car L)) (countIn (cdr L))))
          (else (+ 1 (countIn (cdr L)))))))

(define countObjects
  (lambda (T)
    (countIn (cdr T))))                  ; the name doesn't count

hasRoom

Write hasRoom, which returns #t if a room named R exists anywhere in the room T (T itself counts), and #f otherwise. Objects are not rooms.

(hasRoom 'library House)   ⇒ #t
(hasRoom 'attic House)     ⇒ #f
(hasRoom 'house House)     ⇒ #t
(hasRoom 'skeleton House)  ⇒ #f
(hasRoom 'fridge Kitchen)  ⇒ #t
(hasRoom 'hall Kitchen)    ⇒ #f

Not allowed: flatten, member or memq.

Show answer

True if this room's name matches, or if any sub-room (searched recursively) has it. Objects are never rooms, so skip them.

(define anyHas                           ; is R in any room in L?
  (lambda (R L)
    (cond ((null? L) #f)
          ((list? (car L)) (or (hasRoom R (car L)) (anyHas R (cdr L))))
          (else (anyHas R (cdr L))))))   ; objects aren't rooms

(define hasRoom
  (lambda (R T)
    (or (equal? (car T) R)
        (anyHas R (cdr T)))))

objects

This is the lab problem. Write objects, which finds the first room named R inside T (depth-first, left to right) and returns its objects: the non-list elements after its name. If there's no such room, return '().

The Library can be reached along four different paths, but your answer must contain its objects once.

(objects 'hall House)     ⇒ (suit_of_armour)
(objects 'library House)  ⇒ (book chair)
(objects 'dungeon House)  ⇒ (skeleton)
(objects 'fridge House)   ⇒ (sausages unidentified_head)
(objects 'kitchen House)  ⇒ ()
(objects 'attic House)    ⇒ ()

Not allowed: flatten.

Show answer

First FIND the room, stopping at the first match. Then take its objects. Stopping early is what stops Library's objects appearing four times.

(define keepAtoms
  (lambda (L)
    (cond ((null? L) '())
          ((list? (car L)) (keepAtoms (cdr L)))
          (else (cons (car L) (keepAtoms (cdr L)))))))

(define findRoom                         ; the first room named R, or #f
  (lambda (R T)
    (cond ((equal? (car T) R) T)
          (else (findIn R (cdr T))))))

(define findIn
  (lambda (R L)
    (cond ((null? L) #f)
          ((list? (car L))
           (let ((found (findRoom R (car L))))
             (if found found (findIn R (cdr L)))))   ; stop at the first hit
          (else (findIn R (cdr L))))))

(define objects
  (lambda (R T)
    (let ((room (findRoom R T)))
      (if room (keepAtoms (cdr room)) '()))))

whereIs

Write whereIs, which returns the name of the first room (depth-first, left to right, starting with T itself) that directly contains the object X, or #f if no room does. Room names are not objects.

(whereIs 'book House)     ⇒ library
(whereIs 'ghost House)    ⇒ bathroom
(whereIs 'spade Cottage)  ⇒ garden
(whereIs 'rats Cottage)   ⇒ cottage
(whereIs 'unicorn House)  ⇒ #f
(whereIs 'library House)  ⇒ #f

Not allowed: flatten.

Show answer

Check this room's own objects first. If X isn't there, search the sub-rooms in order and return the first name found, or #f.

(define keepAtoms
  (lambda (L)
    (cond ((null? L) '())
          ((list? (car L)) (keepAtoms (cdr L)))
          (else (cons (car L) (keepAtoms (cdr L)))))))

(define searchRooms                      ; try each sub-room in L, in order
  (lambda (X L)
    (cond ((null? L) #f)
          ((list? (car L))
           (let ((found (whereIs X (car L))))
             (if found found (searchRooms X (cdr L)))))
          (else (searchRooms X (cdr L))))))

(define whereIs
  (lambda (X T)
    (cond ((member X (keepAtoms (cdr T))) (car T))   ; directly in T
          (else (searchRooms X (cdr T))))))

allRooms

Write allRooms, which returns the names of every room in T, including T itself, in the order you first meet them (depth-first, left to right), with no duplicates. Many rooms are reachable along several paths, but each name appears once, in the position where it's first met.

(allRooms Library)  ⇒ (library)
(allRooms Dungeon)  ⇒ (dungeon library)
(allRooms Kitchen)  ⇒ (kitchen cellar dungeon library fridge)
(allRooms Cottage)  ⇒ (cottage garden shed)
(allRooms House)    ⇒ (house hall diningRoom library kitchen cellar dungeon fridge bedroom bathroom)

Not allowed: remove-duplicates or flatten.

Show answer

Collect every room name depth-first, duplicates included. Then keep only the first copy of each name.

(define namesOf                          ; every room name, duplicates included
  (lambda (T)
    (cons (car T) (namesIn (cdr T)))))

(define namesIn
  (lambda (L)
    (cond ((null? L) '())
          ((list? (car L)) (append (namesOf (car L)) (namesIn (cdr L))))
          (else (namesIn (cdr L))))))

(define uniq                             ; keep the first copy of each
  (lambda (L)
    (cond ((null? L) '())
          (else (cons (car L)
                      (uniq (filter (lambda (y) (not (equal? y (car L))))
                                    (cdr L))))))))

(define allRooms
  (lambda (T)
    (uniq (namesOf T))))

roomsWith

Write roomsWith, which returns the names of every room in T (including T) that directly contains the object X, in the order they're first met, with no duplicates.

(roomsWith 'rats Cottage)   ⇒ (cottage shed)
(roomsWith 'spade Cottage)  ⇒ (garden shed)
(roomsWith 'rats House)     ⇒ (cellar)
(roomsWith 'book House)     ⇒ (library)
(roomsWith 'unicorn House)  ⇒ ()

Not allowed: remove-duplicates or flatten.

Show answer

List every room depth-first, keep those whose own objects include X, take their names, and remove duplicates.

(define keepAtoms
  (lambda (L)
    (cond ((null? L) '())
          ((list? (car L)) (keepAtoms (cdr L)))
          (else (cons (car L) (keepAtoms (cdr L)))))))

(define roomsOf                          ; every room structure, depth-first
  (lambda (T)
    (cons T (roomsIn (cdr T)))))

(define roomsIn
  (lambda (L)
    (cond ((null? L) '())
          ((list? (car L)) (append (roomsOf (car L)) (roomsIn (cdr L))))
          (else (roomsIn (cdr L))))))

(define uniq
  (lambda (L)
    (cond ((null? L) '())
          (else (cons (car L)
                      (uniq (filter (lambda (y) (not (equal? y (car L))))
                                    (cdr L))))))))

(define roomsWith
  (lambda (X T)
    (uniq (map car
               (filter (lambda (room) (member X (keepAtoms (cdr room))))
                       (roomsOf T))))))

pathTo

Write pathTo, which returns the list of room names leading from T down to the first room named R (depth-first, left to right). The path starts with T's own name and ends with R. If there's no such room, return #f.

(pathTo 'hall House)     ⇒ (house hall)
(pathTo 'house House)    ⇒ (house)
(pathTo 'library House)  ⇒ (house hall diningRoom library)
(pathTo 'dungeon House)  ⇒ (house hall diningRoom kitchen cellar dungeon)
(pathTo 'attic House)    ⇒ #f
(pathTo 'spade Cottage)  ⇒ #f
Show answer

If this room is the target, the path is just its name. Otherwise find a path from a sub-room and put this room's name in front, or return #f if no sub-room leads there.

(define pathIn                           ; path from the first sub-room in L that leads to R
  (lambda (R L)
    (cond ((null? L) #f)
          ((list? (car L))
           (let ((p (pathTo R (car L))))
             (if p p (pathIn R (cdr L)))))
          (else (pathIn R (cdr L))))))

(define pathTo
  (lambda (R T)
    (cond ((equal? (car T) R) (list (car T)))
          (else (let ((p (pathIn R (cdr T))))
                  (if p (cons (car T) p) #f))))))   ; put this room's name in front

deepestRoom

Depth is counted from T: T has depth 0, a room directly inside it has depth 1, and so on. Write deepestRoom, which returns the name of the room with the greatest depth. If several rooms share the greatest depth, return the one met first (depth-first, left to right).

(deepestRoom Fridge)                      ⇒ fridge
(deepestRoom Cottage)                     ⇒ shed
(deepestRoom Bedroom)                     ⇒ library
(deepestRoom House)                       ⇒ library
(deepestRoom '(top (left) (right)))       ⇒ left
(deepestRoom '(top (a (b)) (c (d (e)))))  ⇒ e

Not allowed: argmax or sort.

Show answer

Record (name depth) for every room depth-first, then pick the deepest. Replacing only on STRICTLY deeper keeps the first one met on a tie.

(define depthsOf                         ; ((name depth) ...) depth-first
  (lambda (T d)
    (cons (list (car T) d) (depthsIn (cdr T) (+ d 1)))))

(define depthsIn
  (lambda (L d)
    (cond ((null? L) '())
          ((list? (car L)) (append (depthsOf (car L) d) (depthsIn (cdr L) d)))
          (else (depthsIn (cdr L) d)))))

(define deepest                          ; best = (name depth) so far
  (lambda (best L)
    (cond ((null? L) best)
          ((> (cadr (car L)) (cadr best)) (deepest (car L) (cdr L)))   ; strictly deeper
          (else (deepest best (cdr L))))))

(define deepestRoom
  (lambda (T)
    (let ((all (depthsOf T 0)))
      (car (deepest (car all) (cdr all))))))

Map, apply and variable arguments

squareAll

Write squareAll, which takes a list of numbers and returns a list of their squares.

Don't write any recursion this time. Use map: (map f L) calls f on every element of L and collects the answers in a new list.

(squareAll '(1 2 3))   ⇒ (1 4 9)
(squareAll '())        ⇒ ()
(squareAll '(-4))      ⇒ (16)
(squareAll '(0 5 10))  ⇒ (0 25 100)

Not allowed: for-each, foldl or foldr.

Show answer

map applies the lambda to every element, so there's no recursion and no base case to write.

(define squareAll
  (lambda (L)
    (map (lambda (x) (* x x)) L)))

addLists

Write addLists, which takes two lists of numbers of the same length and returns a list of their pairwise sums.

No recursion: map can walk through several lists side by side. (map f L1 L2) calls (f first-of-L1 first-of-L2), then (f second-of-L1 second-of-L2), and so on.

(addLists '(1 2 3) '(10 20 30))   ⇒ (11 22 33)
(addLists '() '())                ⇒ ()
(addLists '(5) '(-5))             ⇒ (0)
(addLists '(1 1 1 1) '(0 1 2 3))  ⇒ (1 2 3 4)

Not allowed: for-each, foldl or foldr.

Show answer

map can walk two lists in step: (map + A B) adds them position by position.

(define addLists
  (lambda (A B)
    (map + A B)))

average (list version)

Write average, which returns the mean of a non-empty list of numbers. (Every test divides evenly.)

No recursion: use apply. (apply + '(1 2 3)) means the same as (+ 1 2 3). It spreads the list out into separate arguments.

(average '(2 4 6))      ⇒ 4
(average '(10))         ⇒ 10
(average '(1 2 3 4 5))  ⇒ 3
(average '(-3 3))       ⇒ 0

Not allowed: foldl or foldr.

Show answer

(apply + L) spreads the list into +; divide by length.

(define average
  (lambda (L)
    (/ (apply + L) (length L))))

myList

Write your own version of the built-in list: myList takes any number of arguments and returns them in a list.

A lambda whose parameter has no brackets around it, like (lambda args …), takes any number of arguments, and args is a list of all of them. Compare: (lambda (args) …) takes exactly ONE argument.

(myList 1 2 3)           ⇒ (1 2 3)
(myList)                 ⇒ ()
(myList '(a b))          ⇒ ((a b))
(myList 'x (myList 'y))  ⇒ (x (y))

Not allowed: list or list*.

Show answer

(lambda args args): the arguments arrive as a list, and that list is the answer.

(define myList
  (lambda args                           ; args is already the list we want
    args))

pickOne

Write pickOne, which takes one or more arguments and returns one of them, chosen at random.

(random N) gives a random whole number from 0 to N−1. (list-ref L i) gives element number i of L, counting from 0.

(if (member (pickOne 'work 'rest 'play) '(work rest play)) #t #f)
  ⇒ #t
(pickOne 'only)
  ⇒ only
(let loop ((i 0) (a #f) (b #f)) (if (= i 60) (and a b) (let ((x (pickOne 1 2))) (loop (+ i 1) (or a (= x 1)) (or b (= x 2))))))
  ⇒ #t
Show answer

Collect the arguments, pick a random index below the length, and fetch it with list-ref.

(define pickOne
  (lambda args
    (list-ref args (random (length args)))))

applyOp

Op is a symbol naming a function, like '+, 'max or 'list. L is a list of numbers. Write applyOp, which returns the result of calling that function on the numbers in L.

Build the expression as a list, e.g. (+ 1 2 3), then run it with eval. apply is off-limits here so that you practise eval.

(Note for Moodle: there, eval may be called primitive-eval. You can write (define eval primitive-eval) at the top.)

(applyOp '+ '(1 2 3))    ⇒ 6
(applyOp 'max '(3 9 2))  ⇒ 9
(applyOp '* '())         ⇒ 1
(applyOp 'list '(1 2))   ⇒ (1 2)

Not allowed: apply.

Show answer

Build the code as data, e.g. (+ 1 2 3) from (cons Op L), then run it with eval.

(define applyOp
  (lambda (Op L)
    (eval (cons Op L))))                 ; builds e.g. (+ 1 2 3) and runs it

myMax

Write myMax, which takes one or more numbers and returns the largest. You can't use the built-in max.

A parameter list like (x . rest) means: the first argument goes in x, and a list of all the others goes in rest. You can write it as (define myMax (lambda (x . rest) …)).

(myMax 3)            ⇒ 3
(myMax 3 9 2)        ⇒ 9
(myMax -5 -2 -9)     ⇒ -2
(myMax 4 4 1)        ⇒ 4
(myMax 1 2 3 4 5 6)  ⇒ 6

Not allowed: max, argmax, foldl, foldr or sort.

Show answer

(x . rest) names the first argument. The max of the rest comes from (apply myMax rest), then compare it with x.

(define myMax
  (lambda (x . rest)
    (cond ((null? rest) x)
          (else (let ((m (apply myMax rest)))    ; biggest of the others
                  (if (> x m) x m))))))

countBigger

Write countBigger, which takes a number N followed by any number of numbers, and returns how many of those numbers are strictly bigger than N.

Solve it by recursion on countBigger itself (filter is switched off). You'll need the full form of apply: (apply f a b L) means (f a b followed by the elements of L).

(countBigger 5 1 7 3 9)     ⇒ 2
(countBigger 0)             ⇒ 0
(countBigger 2 2 2 3)       ⇒ 1
(countBigger -1 0 -1 -2 5)  ⇒ 2

Not allowed: filter, filter-not, count, foldl, foldr or length.

Show answer

Recurse on the arguments with (apply countBigger N (cdr nums)), which keeps N in front and spreads the rest of the numbers back out.

(define countBigger
  (lambda (N . nums)
    (cond ((null? nums) 0)
          ((> (car nums) N) (+ 1 (apply countBigger N (cdr nums))))
          (else (apply countBigger N (cdr nums))))))

nestList

Write nestList, which takes one or more arguments and nests them, each one inside the list of the one before it:

  • (nestList 1 2 3) gives (1 (2 (3)))
  • (nestList 'a) gives (a)
(nestList 1 2 3)    ⇒ (1 (2 (3)))
(nestList 'a)       ⇒ (a)
(nestList 'a 'b)    ⇒ (a (b))
(nestList '(x) 'y)  ⇒ ((x) (y))
Show answer

One argument becomes (x). Otherwise (list x nested-rest) puts the rest one level deeper.

(define nestList
  (lambda (x . rest)
    (cond ((null? rest) (list x))
          (else (list x (apply nestList rest))))))

sumColumns

M is a matrix: a non-empty list of rows, all the same length. Write sumColumns, which returns a list of the column totals.

(sumColumns '((1 2 3) (4 5 6))) gives (5 7 9).

This can be done in one line with no recursion.

(sumColumns '((1 2 3) (4 5 6)))                  ⇒ (5 7 9)
(sumColumns '((1 2)))                            ⇒ (1 2)
(sumColumns '((1) (2) (3)))                      ⇒ (6)
(sumColumns '((1 0 0) (0 1 0) (0 0 1) (2 2 2)))  ⇒ (3 3 3)

Not allowed: foldl, foldr or for-each.

Show answer

(apply map + M) turns into (map + row1 row2 …), which adds straight down each column.

;; (apply map + M) is (map + row1 row2 ...), which adds down each column
(define sumColumns
  (lambda (M)
    (apply map + M)))

zipAll

Write zipAll, which takes one or more lists of the same length and groups their elements by position:

(zipAll '(1 2) '(a b) '(x y)) gives ((1 a x) (2 b y)).

(zipAll '(1 2) '(a b))         ⇒ ((1 a) (2 b))
(zipAll '(1 2) '(a b) '(x y))  ⇒ ((1 a x) (2 b y))
(zipAll '(1 2 3))              ⇒ ((1) (2) (3))
(zipAll '() '())               ⇒ ()

Not allowed: foldl, foldr or for-each.

Show answer

(apply map list lists) turns into (map list L1 L2 …), grouping the elements by position.

(define zipAll
  (lambda lists
    (apply map list lists)))

composeAll

Write composeAll, which takes any number of one-argument functions and returns a single new function that applies them right to left:

((composeAll f g h) x) means (f (g (h x))).

With no functions at all, composeAll returns a function that gives back its input unchanged.

((composeAll car cdr cdr) '(1 2 3))
  ⇒ 3
((composeAll) 5)
  ⇒ 5
((composeAll (lambda (x) (* x 2)) (lambda (x) (+ x 1))) 5)
  ⇒ 12
((composeAll length) '(a b))
  ⇒ 2
(map (composeAll car reverse) '((1 2) (3 4 5)))
  ⇒ (2 5)

Not allowed: compose, compose1, foldl or foldr.

Show answer

No functions gives the identity. Otherwise apply the first function to the result of composing the rest, which gives right-to-left order.

(define composeAll
  (lambda fns
    (lambda (x)
      (cond ((null? fns) x)
            (else ((car fns)
                   ((apply composeAll (cdr fns)) x)))))))

myMapN

Write myMapN, your own version of map that takes a function F and one or more lists, all the same length. It calls F on the first elements of every list, then the second elements, and so on:

  • (myMapN + '(1 2 3) '(10 20 30)) gives (11 22 33)
  • (myMapN - '(5 6)) gives (-5 -6)

The built-in map is switched off, so you'll need helpers to take the cars and the cdrs of a list of lists.

(myMapN + '(1 2 3) '(10 20 30))
  ⇒ (11 22 33)
(myMapN - '(5 6))
  ⇒ (-5 -6)
(myMapN list '(1 2) '(a b) '(x y))
  ⇒ ((1 a x) (2 b y))
(myMapN + '() '())
  ⇒ ()
(myMapN (lambda (a b c) (+ a (* b c))) '(1 2) '(3 4) '(5 6))
  ⇒ (16 26)

Not allowed: map, for-each, andmap, ormap, foldl, foldr, append-map or filter-map.

Show answer

Take the cars of every list for one call of F and the cdrs for the recursion. Stop when the lists are empty.

(define cars                             ; first element of every list
  (lambda (LL)
    (cond ((null? LL) '())
          (else (cons (car (car LL)) (cars (cdr LL)))))))

(define cdrs                             ; every list minus its first element
  (lambda (LL)
    (cond ((null? LL) '())
          (else (cons (cdr (car LL)) (cdrs (cdr LL)))))))

(define myMapN
  (lambda (F . lists)
    (cond ((null? (car lists)) '())
          (else (cons (apply F (cars lists))
                      (apply myMapN F (cdrs lists)))))))

chain

A variable-arity function takes any number of arguments. (lambda args ...) puts ALL the arguments in a list called args; (lambda (f . rest) ...) names the first one and puts the rest in a list. Write chain, which takes any number of one-argument functions followed by a value. It calls the LAST function on the value, then the one before it on that result, and so on, back to the first.

(chain list (lambda (x) (+ x 2)) sqrt 25)  ⇒ (7)
(chain sqrt sqrt 625)                      ⇒ 5
(chain list list list list 'hugs)          ⇒ ((((hugs))))
(chain sqrt sqrt sqrt sqrt sqrt 5)         ⇒ 1.0515811984959769
(chain - 3)                                ⇒ -3
Show answer

The last argument is the value. If only it is left, return it. Otherwise apply the first function to the chain of the rest.

(define chain
  (lambda args
    (cond ((null? (cdr args)) (car args))          ; only the value is left
          (else ((car args) (apply chain (cdr args)))))))

chainLeft

Write chainLeft: like chain, but it calls the FIRST function on the value, then the second function on that result, and so on to the last. (The value is still the last argument.)

(chainLeft sqrt (lambda (x) (+ x 2)) list 25)             ⇒ (7)
(chainLeft cdr cdr car '(a b c d))                        ⇒ c
(chainLeft (lambda (x) (* x 10)) (lambda (x) (+ x 1)) 4)  ⇒ 41
(chainLeft (lambda (x) (+ x 1)) (lambda (x) (* x 10)) 4)  ⇒ 50
Show answer

Reverse the arguments so the value comes first, put the functions back in order, then apply them left to right.

;; apply fns in order, first to last
(define runLeft
  (lambda (fns x)
    (cond ((null? fns) x)
          (else (runLeft (cdr fns) ((car fns) x))))))

(define chainLeft
  (lambda args
    (let ((r (reverse args)))            ; value is now first, functions reversed
      (runLeft (reverse (cdr r)) (car r)))))

chainTrace

Write chainTrace, which works like chain (last function first) but returns every intermediate value: the starting value first, then each result in order, ending with the final answer.

(chainTrace list (lambda (x) (+ x 2)) sqrt 25)            ⇒ (25 5 7 (7))
(chainTrace - 4)                                          ⇒ (4 -4)
(chainTrace car cdr '(1 2 3))                             ⇒ ((1 2 3) (2 3) 2)
(chainTrace (lambda (x) (* x x)) (lambda (x) (* x x)) 3)  ⇒ (3 9 81)
Show answer

Like chain, but output every intermediate value, starting with the original one.

;; fns are in the order they get applied
(define traceRun
  (lambda (fns x)
    (cond ((null? fns) (list x))
          (else (cons x (traceRun (cdr fns) ((car fns) x)))))))

(define chainTrace
  (lambda args
    (let ((r (reverse args)))            ; (value lastFn ... firstFn)
      (traceRun (cdr r) (car r)))))

chainOrFalse

Write chainOrFalse: like chain (last function first), but if any step returns #f, stop straight away and return #f without calling the remaining functions.

(chainOrFalse (lambda (x) (* x 10)) (lambda (x) (if (> x 0) x #f)) 5)
  ⇒ 50
(chainOrFalse (lambda (x) (* x 10)) (lambda (x) (if (> x 0) x #f)) -5)
  ⇒ #f
(chainOrFalse car (lambda (L) (if (null? L) #f L)) '())
  ⇒ #f
(chainOrFalse car (lambda (L) (if (null? L) #f L)) '(9))
  ⇒ 9
Show answer

Compute the later steps first. If they produced #f, return #f without calling the current function.

(define chainOrFalse
  (lambda args
    (cond ((null? (cdr args)) (car args))
          (else (let ((v (apply chainOrFalse (cdr args))))   ; result of the later steps
                  (cond ((equal? v #f) #f)                    ; stop: don't call (car args)
                        (else ((car args) v))))))))

pipeAll

Write pipeAll, which takes any number of one-argument functions and RETURNS a new function of one argument that runs them in order: the first function first, then the second, and so on. With no functions it returns its input unchanged.

((pipeAll cdr car) '(1 2 3))                             ⇒ 2
((pipeAll (lambda (x) (+ x 1)) (lambda (x) (* x 2))) 5)  ⇒ 12
((pipeAll) 42)                                           ⇒ 42
(map (pipeAll car -) '((1) (2)))                         ⇒ (-1 -2)
Show answer

Return a lambda that runs the remembered functions left to right on its input.

(define runLeft
  (lambda (fns x)
    (cond ((null? fns) x)
          (else (runLeft (cdr fns) ((car fns) x))))))

(define pipeAll
  (lambda fns
    (lambda (x)
      (runLeft fns x))))

partial

Write partial, which takes a function f and some of its first arguments, and returns a new function that takes the REMAINING arguments (any number) and calls f with all of them in order.

((partial + 1 2) 3 4)         ⇒ 10
((partial list 'a) 'b 'c)     ⇒ (a b c)
((partial - 10) 3)            ⇒ 7
((partial max) 4 9 2)         ⇒ 9
(map (partial * 3) '(1 2 3))  ⇒ (3 6 9)
Show answer

Remember the first arguments. When the rest arrive, apply f to all of them joined with append.

(define partial
  (lambda (f . first)
    (lambda rest
      (apply f (append first rest)))))

reverseArgs

Write reverseArgs, which takes a function f and returns a new function that accepts any number of arguments and calls f with them in reverse order.

((reverseArgs list) 1 2 3)    ⇒ (3 2 1)
((reverseArgs -) 1 10)        ⇒ 9
((reverseArgs cons) '(b) 'a)  ⇒ (a b)
((reverseArgs list))          ⇒ ()
Show answer

Return a variable-arity lambda that applys f to its arguments reversed.

(define reverseArgs
  (lambda (f)
    (lambda args
      (apply f (reverse args)))))

applyEach

Write applyEach, which takes a value x followed by any number of one-argument functions, and returns the list of (f x) for each function, in order.

(applyEach 9 sqrt - list)                ⇒ (3 -9 (9))
(applyEach '(1 2 3) car cdr length)      ⇒ (1 (2 3) 3)
(applyEach 5)                            ⇒ ()
(applyEach -4 abs (lambda (n) (* n n)))  ⇒ (4 16)
Show answer

(x . fns) names the value. map over the functions, calling each one on x.

(define applyEach
  (lambda (x . fns)
    (map (lambda (f) (f x)) fns)))

mapArgs

Write mapArgs, which takes a one-argument function f and any number of further arguments, and returns the list of f applied to each of them.

(mapArgs (lambda (x) (* x x)) 1 2 3)  ⇒ (1 4 9)
(mapArgs car '(a b) '(c) '(d e))      ⇒ (a c d)
(mapArgs -)                           ⇒ ()
(mapArgs list 1)                      ⇒ ((1))
Show answer

(f . args) names the function and collects the rest. Then it's just (map f args).

(define mapArgs
  (lambda (f . args)
    (map f args)))

countWhere

Write countWhere, which takes a predicate followed by any number of values, and returns how many of the values satisfy the predicate.

(countWhere even? 1 2 4 7)        ⇒ 2
(countWhere symbol? 'a 1 'b "c")  ⇒ 2
(countWhere odd?)                 ⇒ 0
(countWhere null? '() '(1) '())   ⇒ 2
Show answer

The values arrive as a list, so filter with the predicate and take the length.

(define countWhere
  (lambda (test? . vals)
    (length (filter test? vals))))

argmax

Write argmax, which takes a scoring function f and one or more values, and returns the VALUE whose (f value) is largest. On a tie return the first such value.

(argmax abs -7 3 5)                       ⇒ -7
(argmax length '(a b) '(c d e) '(f g h))  ⇒ (c d e)
(argmax - 4 1 9)                          ⇒ 1
(argmax (lambda (x) 0) 5 6)               ⇒ 5
Show answer

Best-so-far with a score function. Replace only on a strictly higher score, so ties keep the first.

(define bestOf                           ; best = winner so far
  (lambda (f best L)
    (cond ((null? L) best)
          ((> (f (car L)) (f best)) (bestOf f (car L) (cdr L)))
          (else (bestOf f best (cdr L))))))

(define argmax
  (lambda (f x . rest)
    (bestOf f x rest)))

maxOfAll

Write maxOfAll, which takes any number of lists of numbers and returns the largest number in any of them. At least one number exists somewhere, but some lists may be empty.

(maxOfAll '(1 5) '(9 2) '())    ⇒ 9
(maxOfAll '(-3 -8))             ⇒ -3
(maxOfAll '() '(4) '(4 1))      ⇒ 4
(maxOfAll '(1) '(2) '(3) '(2))  ⇒ 3
Show answer

Join all the lists with apply append, then take apply max once.

(define maxOfAll
  (lambda lists
    (apply max (apply append lists))))   ; join every list, then take the max

longestArg

Write longestArg, which takes one or more lists as separate arguments and returns the longest one (the first one on a tie).

(longestArg '(1) '(2 3) '(4 5))      ⇒ (2 3)
(longestArg '(a b c))                ⇒ (a b c)
(longestArg '() '(x) '())            ⇒ (x)
(longestArg '(1 2) '(3 4 5 6) '(7))  ⇒ (3 4 5 6)
Show answer

Compare the first list with the longest of the rest. >= keeps the earlier one on a tie.

(define longestArg
  (lambda (L . rest)
    (cond ((null? rest) L)
          (else (let ((best (apply longestArg rest)))
                  (if (>= (length L) (length best)) L best))))))   ; >= keeps the first on a tie

countLongest

Write countLongest, which takes one or more lists and returns how many of them have the maximum length.

(countLongest '(1 2) '(3) '(4 5))    ⇒ 2
(countLongest '(a))                  ⇒ 1
(countLongest '() '())               ⇒ 2
(countLongest '(1 2 3) '(1) '(1 2))  ⇒ 1
Show answer

Find the maximum length once, then count the lists with that length.

(define countLongest
  (lambda lists
    (let ((most (apply max (map length lists))))
      (length (filter (lambda (L) (= (length L) most)) lists)))))

sumAll

Write sumAll, which takes any number of arguments, each either a number or a list of numbers, and returns the total of every number.

(sumAll 1 '(2 3) 4)     ⇒ 10
(sumAll)                ⇒ 0
(sumAll '() '(5) 5)     ⇒ 10
(sumAll '(1 2) '(3 4))  ⇒ 10
Show answer

Turn each argument into a number first (a list becomes its sum), then add them all.

(define sumAll
  (lambda args
    (apply + (map (lambda (a) (if (list? a) (apply + a) a))
                  args))))

elementMax

Write elementMax, which takes one or more lists of numbers, all the same length, and returns a list of the largest number in each position.

(elementMax '(1 5 3) '(4 2 6) '(0 9 1))  ⇒ (4 9 6)
(elementMax '(7 8))                      ⇒ (7 8)
(elementMax '() '())                     ⇒ ()
(elementMax '(-1 -2) '(-3 0))            ⇒ (-1 0)
Show answer

(apply map max lists): map walks all the lists in step and takes the max at each position.

(define elementMax
  (lambda lists
    (apply map max lists)))

spread

Write spread, which takes one or more numbers and returns the difference between the largest and the smallest.

(spread 4 9 1 7)  ⇒ 8
(spread 5)        ⇒ 0
(spread -3 3)     ⇒ 6
(spread 2 2 2)    ⇒ 0
Show answer

Biggest minus smallest: (apply max nums) and (apply min nums).

(define spread
  (lambda nums
    (- (apply max nums) (apply min nums))))

maxPosition

Write maxPosition, which takes one or more numbers and returns the position (counting from 0) of the first occurrence of the largest one.

(maxPosition 3 9 2 9)   ⇒ 1
(maxPosition 5)         ⇒ 0
(maxPosition 1 2 3)     ⇒ 2
(maxPosition -1 -5 -1)  ⇒ 0
Show answer

Find the maximum value, then find the position of its first occurrence.

(define posOf                            ; position of the first x in L
  (lambda (x L)
    (cond ((equal? x (car L)) 0)
          (else (+ 1 (posOf x (cdr L)))))))

(define maxPosition
  (lambda nums
    (posOf (apply max nums) nums)))

argCount

When a function is written (lambda args ...) with NO brackets around args, Scheme collects every argument into one list called args. Write argCount, which returns how many arguments it was called with. Careful: a list passed in is ONE argument, however long it is.

(argCount 'a 'b 'c)      ⇒ 3
(argCount)               ⇒ 0
(argCount '(1 2 3 4 5))  ⇒ 1
(argCount '() '())       ⇒ 2
Show answer

All the arguments are in one list, so its length is the number of arguments. A list passed in is still one element.

(define argCount
  (lambda args
    (length args)))

firstAndRest

A dotted parameter list (lambda (a . more) ...) gives the FIRST argument a name and collects every other argument into a list. Write firstAndRest, which returns a two-element list: the first argument, and the list of the rest. It always gets at least one argument.

(firstAndRest 1 2 3)      ⇒ (1 (2 3))
(firstAndRest 'x)         ⇒ (x ())
(firstAndRest '(a b) 'c)  ⇒ ((a b) (c))
(firstAndRest 1 2)        ⇒ (1 (2))
Show answer

The dotted parameter list does the work: a is the first argument and more holds the rest.

(define firstAndRest
  (lambda (a . more)
    (list a more)))

lastArg

Write lastArg, which returns its last argument. It always gets at least one.

(lastArg 1 2 3)      ⇒ 3
(lastArg 'only)      ⇒ only
(lastArg 'a '(b c))  ⇒ (b c)
(lastArg 5 4 3 2 1)  ⇒ 1
Show answer

The last argument is the car of the reversed argument list.

(define lastArg
  (lambda args
    (car (reverse args))))

allEqual

Write allEqual, which returns #t if all of its arguments are equal? to each other (and #t when there are 0 or 1 arguments), otherwise #f.

(allEqual 1 1 1)      ⇒ #t
(allEqual 1 1 2)      ⇒ #f
(allEqual)            ⇒ #t
(allEqual '(a) '(a))  ⇒ #t
(allEqual 'x)         ⇒ #t
Show answer

Compare each neighbouring pair with equal?. Zero or one arguments are trivially all equal.

(define allEqual
  (lambda args
    (cond ((null? args) #t)
          ((null? (cdr args)) #t)
          ((equal? (car args) (cadr args)) (apply allEqual (cdr args)))
          (else #f))))

someArg

Write someArg, which takes a predicate followed by any number of values, and returns #t if at least one value satisfies the predicate, otherwise #f.

(someArg even? 1 3 4)     ⇒ #t
(someArg even? 1 3 5)     ⇒ #f
(someArg even?)           ⇒ #f
(someArg null? '(1) '())  ⇒ #t
Show answer

Return #t at the first value that passes, recursing with apply to keep the predicate in front.

(define someArg
  (lambda (test? . vals)
    (cond ((null? vals) #f)
          ((test? (car vals)) #t)
          (else (apply someArg test? (cdr vals))))))

powerOf

A rest parameter can make an argument OPTIONAL: if the caller leaves it out, the rest list is empty. Write powerOf: (powerOf b e) returns b to the power e, and (powerOf b) squares b (the exponent defaults to 2).

(powerOf 3)     ⇒ 9
(powerOf 2 5)   ⇒ 32
(powerOf 10 0)  ⇒ 1
(powerOf -2 3)  ⇒ -8
Show answer

The optional exponent arrives as a list: '() if it was left out (use 2), otherwise (e).

(define powerOf
  (lambda (b . opt)                      ; opt is () or (e)
    (cond ((null? opt) (expt b 2))
          (else (expt b (car opt))))))

myRange

Write myRange, which builds a list of numbers like Python's range: (myRange stop) counts from 0 up to (not including) stop; (myRange start stop) counts from start; (myRange start stop step) goes up in steps of step (step is always positive).

(myRange 5)       ⇒ (0 1 2 3 4)
(myRange 2 5)     ⇒ (2 3 4)
(myRange 0 10 3)  ⇒ (0 3 6 9)
(myRange 0)       ⇒ ()
(myRange 5 2)     ⇒ ()
Show answer

Count the arguments to decide which form was used, then call one helper (rangeFrom start stop step).

(define rangeFrom
  (lambda (a b step)
    (cond ((>= a b) '())
          (else (cons a (rangeFrom (+ a step) b step))))))

(define myRange
  (lambda args
    (cond ((null? (cdr args)) (rangeFrom 0 (car args) 1))              ; (stop)
          ((null? (cddr args)) (rangeFrom (car args) (cadr args) 1))   ; (start stop)
          (else (rangeFrom (car args) (cadr args) (caddr args))))))    ; (start stop step)

groupArgs

Write groupArgs, which takes a group size n (at least 1) followed by any number of values, and returns the values in groups of n. The last group may be shorter.

(groupArgs 2 1 2 3 4 5)  ⇒ ((1 2) (3 4) (5))
(groupArgs 3 'a 'b 'c)   ⇒ ((a b c))
(groupArgs 2)            ⇒ ()
(groupArgs 1 7 8)        ⇒ ((7) (8))
Show answer

(n . vals) names the size. Then take the first n as a group, skip them, and repeat.

(define firstN
  (lambda (n L)
    (cond ((or (= n 0) (null? L)) '())
          (else (cons (car L) (firstN (- n 1) (cdr L)))))))

(define skipN
  (lambda (n L)
    (cond ((or (= n 0) (null? L)) L)
          (else (skipN (- n 1) (cdr L))))))

(define groups
  (lambda (n L)
    (cond ((null? L) '())
          (else (cons (firstN n L) (groups n (skipN n L)))))))

(define groupArgs
  (lambda (n . vals)
    (groups n vals)))

callWithBoth

(apply f '(1 2 3)) means the same as (f 1 2 3): it spreads the list out into separate arguments. Write callWithBoth, which calls f with all the elements of L1 followed by all the elements of L2 as separate arguments.

(callWithBoth + '(1 2) '(3))     ⇒ 6
(callWithBoth list '(a) '(b c))  ⇒ (a b c)
(callWithBoth max '() '(4 9 2))  ⇒ 9
(callWithBoth - '(10) '(1 2))    ⇒ 7
Show answer

Join the two lists, then apply f so every element becomes a separate argument.

(define callWithBoth
  (lambda (f L1 L2)
    (apply f (append L1 L2))))

prependCall

apply can take ordinary arguments BEFORE the final list: (apply f 1 2 '(3 4)) means (f 1 2 3 4). Write prependCall, which calls f with x first, then every element of L. Try it without cons or append.

(prependCall - 10 '(1 2))     ⇒ 7
(prependCall list 'a '(b c))  ⇒ (a b c)
(prependCall max 3 '())       ⇒ 3
(prependCall cons 'x '((y)))  ⇒ (x y)

Not allowed: cons or append.

Show answer

apply accepts loose arguments before the final list: (apply f x L) is (f x l1 l2 …).

(define prependCall
  (lambda (f x L)
    (apply f x L)))

maxOfMaxes

LL is a list of non-empty lists of numbers. Write maxOfMaxes, which returns the biggest number anywhere, by first finding each inner list's maximum and then the maximum of those.

(maxOfMaxes '((1 5) (9 2) (4)))  ⇒ 9
(maxOfMaxes '((-3 -8)))          ⇒ -3
(maxOfMaxes '((1) (2) (3)))      ⇒ 3
(maxOfMaxes '((7 7) (7)))        ⇒ 7
Show answer

map each inner list to its own max, then take the max of those.

(define maxOfMaxes
  (lambda (LL)
    (apply max (map (lambda (L) (apply max L)) LL))))

applyPairs

PS is a list of argument lists. Write applyPairs, which calls f once per argument list, spreading it out, and returns the list of results.

(applyPairs + '((1 2) (3 4)))        ⇒ (3 7)
(applyPairs cons '((a (b)) (c ())))  ⇒ ((a b) (c))
(applyPairs max '((1 9 3) (4)))      ⇒ (9 4)
(applyPairs list '())                ⇒ ()
Show answer

map over the argument lists, applying f to each one.

(define applyPairs
  (lambda (f PS)
    (map (lambda (args) (apply f args)) PS)))

logCall

Write logCall, which takes a function f and any arguments, calls f with those arguments, and returns a two-element list: the list of arguments, and the result.

(logCall + 1 2)      ⇒ ((1 2) 3)
(logCall list 'a)    ⇒ ((a) (a))
(logCall max 4 9 2)  ⇒ ((4 9 2) 9)
(logCall +)          ⇒ (() 0)
Show answer

Return a list of the arguments and the result of (apply f args).

(define logCall
  (lambda (f . args)
    (list args (apply f args))))

zipPairs

map can take several lists and walks them in step: (map + '(1 2) '(10 20)) gives (11 22). Write zipPairs, which pairs the elements of two equal-length lists into two-element lists. Use map, not recursion.

(zipPairs '(1 2 3) '(a b c))  ⇒ ((1 a) (2 b) (3 c))
(zipPairs '() '())            ⇒ ()
(zipPairs '(x) '((y)))        ⇒ ((x (y)))
(zipPairs '(1 2) '(1 2))      ⇒ ((1 1) (2 2))
Show answer

(map list A B) pairs elements by position.

(define zipPairs
  (lambda (A B)
    (map list A B)))

dot

Write dot: multiply the two equal-length lists of numbers position by position, then add up the products. One line with map and apply.

(dot '(1 2 3) '(4 5 6))  ⇒ 32
(dot '() '())            ⇒ 0
(dot '(2) '(-3))         ⇒ -6
(dot '(1 0 1) '(5 9 5))  ⇒ 10
Show answer

Multiply position by position with (map * A B), then add the products with apply +.

(define dot
  (lambda (A B)
    (apply + (map * A B))))

flipRows

M is a matrix: a non-empty list of rows, all the same length. Write flipRows, which turns rows into columns. Hint of the decade: if you could write (map list row1 row2 row3), map would walk all the rows at once.

(flipRows '((1 2 3) (4 5 6)))  ⇒ ((1 4) (2 5) (3 6))
(flipRows '((1 2) (3 4)))      ⇒ ((1 3) (2 4))
(flipRows '((a b c)))          ⇒ ((a) (b) (c))
(flipRows '((1) (2) (3)))      ⇒ ((1 2 3))
Show answer

(apply map list M) is (map list row1 row2 …), which collects each column into a row.

(define flipRows
  (lambda (M)
    (apply map list M)))                 ; = (map list row1 row2 ...)

addMatrices

Write addMatrices, which adds two matrices of the same shape element by element.

(addMatrices '((1 2) (3 4)) '((10 20) (30 40)))  ⇒ ((11 22) (33 44))
(addMatrices '((1)) '((-1)))                     ⇒ ((0))
(addMatrices '((1 2 3)) '((1 1 1)))              ⇒ ((2 3 4))
(addMatrices '((5) (6)) '((1) (2)))              ⇒ ((6) (8))
Show answer

Use map twice: over pairs of rows, then within each pair of rows with +.

(define addMatrices
  (lambda (A B)
    (map (lambda (rowA rowB) (map + rowA rowB)) A B)))

mapWithIndex

Write mapWithIndex, which calls (f i x) for each element x of L together with its position i (from 0), and returns the results.

(mapWithIndex list '(a b c))
  ⇒ ((0 a) (1 b) (2 c))
(mapWithIndex + '(10 10 10))
  ⇒ (10 11 12)
(mapWithIndex * '())
  ⇒ ()
(mapWithIndex (lambda (i x) (if (even? i) x 0)) '(5 6 7 8))
  ⇒ (5 0 7 0)
Show answer

Build the list of positions (0 1 2 …), then map over the positions and the elements together.

(define countUp                          ; (i i+1 ... n-1)
  (lambda (i n)
    (cond ((= i n) '())
          (else (cons i (countUp (+ i 1) n))))))

(define mapWithIndex
  (lambda (f L)
    (map f (countUp 0 (length L)) L)))

rowMaxes

Write rowMaxes, which returns a list of two lists: the maximum of each row of the matrix M, then the maximum of each column.

(rowMaxes '((1 9) (7 2)))      ⇒ ((9 7) (7 9))
(rowMaxes '((5)))              ⇒ ((5) (5))
(rowMaxes '((1 2 3) (6 5 4)))  ⇒ ((3 6) (6 5 4))
(rowMaxes '((-1 -5) (-3 -2)))  ⇒ ((-1 -2) (-1 -2))
Show answer

Row maxima: map apply max over the rows. Column maxima: (apply map max M).

(define rowMaxes
  (lambda (M)
    (list (map (lambda (row) (apply max row)) M)
          (apply map max M))))           ; max down each column

juxtAll

Write juxtAll, which takes any number of one-argument functions and returns a new function of one argument x that returns the list of every function's result on x, in order.

((juxtAll car cdr length) '(1 2 3))      ⇒ (1 (2 3) 3)
((juxtAll - abs) -4)                     ⇒ (4 4)
((juxtAll) 7)                            ⇒ ()
(map (juxtAll car cadr) '((a b) (c d)))  ⇒ ((a b) (c d))
Show answer

Return a lambda that maps over the remembered functions, calling each one on x.

(define juxtAll
  (lambda fns
    (lambda (x)
      (map (lambda (f) (f x)) fns))))

everyPred

Write everyPred, which takes any number of predicates and returns ONE predicate that is true only when every one of them is true for its argument. Stop checking as soon as one fails. With no predicates it is always true.

((everyPred number? positive? even?) 4)          ⇒ #t
((everyPred number? positive? even?) 3)          ⇒ #f
((everyPred number? positive?) 'a)               ⇒ #f
((everyPred) 'anything)                          ⇒ #t
(filter (everyPred odd? positive?) '(-3 1 2 5))  ⇒ (1 5)
Show answer

Return a predicate that checks the remembered predicates in order and stops at the first failure.

(define passesAll
  (lambda (preds x)
    (cond ((null? preds) #t)
          (((car preds) x) (passesAll (cdr preds) x))
          (else #f))))                   ; stop at the first failure

(define everyPred
  (lambda preds
    (lambda (x)
      (passesAll preds x))))

intersectAll

Write intersectAll, which takes one or more lists and returns the elements of the FIRST list that appear in every other list, in the first list's order.

(intersectAll '(1 2 3 4) '(2 4 6) '(4 2))  ⇒ (2 4)
(intersectAll '(a b c))                    ⇒ (a b c)
(intersectAll '(1 2) '(3))                 ⇒ ()
(intersectAll '(x y) '(y x) '(x) '(z x))   ⇒ (x)
Show answer

Keep the elements of the first list that are member of every other list.

(define inEvery                          ; is x in every list of LL?
  (lambda (x LL)
    (cond ((null? LL) #t)
          ((member x (car LL)) (inEvery x (cdr LL)))
          (else #f))))

(define intersectAll
  (lambda (first . others)
    (filter (lambda (x) (inEvery x others)) first)))

unionAll

Write unionAll, which takes any number of lists and returns every distinct element that appears in any of them, each once, in the order it is first seen (reading the lists left to right).

(unionAll '(a b) '(b c) '(c d a))  ⇒ (a b c d)
(unionAll)                         ⇒ ()
(unionAll '(1 1 2))                ⇒ (1 2)
(unionAll '() '(x) '())            ⇒ (x)

Not allowed: remove-duplicates.

Show answer

Join all the lists, then keep only the first copy of each element.

;; keep the first copy of each element, drop the later copies
(define uniq
  (lambda (L)
    (cond ((null? L) '())
          (else (cons (car L)
                      (uniq (filter (lambda (y) (not (equal? y (car L))))
                                    (cdr L))))))))

(define unionAll
  (lambda lists
    (uniq (apply append lists))))

flattenArgs

Write flattenArgs, which takes any number of arguments, each an atom or a (possibly nested) list, and returns one flat list of every atom, in order.

(flattenArgs 1 '(2 3) '((4)) 5)  ⇒ (1 2 3 4 5)
(flattenArgs)                    ⇒ ()
(flattenArgs '(a (b (c))) 'd)    ⇒ (a b c d)
(flattenArgs '() '(()))          ⇒ ()

Not allowed: flatten.

Show answer

The arguments are already one list, so flatten that list with the usual deep recursion.

(define flat
  (lambda (L)
    (cond ((null? L) '())
          ((list? (car L)) (append (flat (car L)) (flat (cdr L))))
          (else (cons (car L) (flat (cdr L)))))))

(define flattenArgs
  (lambda args
    (flat args)))                        ; the arguments are just one big list

matMul

Write matMul, which multiplies matrix A (n×m) by matrix B (m×p). Entry (i, j) of the answer is the dot product of row i of A with column j of B.

(matMul '((1 2) (3 4)) '((5 6) (7 8)))  ⇒ ((19 22) (43 50))
(matMul '((1 0) (0 1)) '((9 8) (7 6)))  ⇒ ((9 8) (7 6))
(matMul '((1 2 3)) '((1) (2) (3)))      ⇒ ((14))
(matMul '((2)) '((3 4)))                ⇒ ((6 8))
Show answer

Transpose B once to get its columns. Each entry is then the dot product of a row and a column, using nested maps.

(define matMul
  (lambda (A B)
    (let ((cols (apply map list B)))     ; columns of B
      (map (lambda (row)
             (map (lambda (col) (apply + (map * row col)))
                  cols))
           A))))

calc

E is either a number or a list (op arg ...) where op is one of the symbols + - * max min and each arg is itself an expression. Write calc, which evaluates it. This is how Scheme itself evaluates code: work out the arguments, then apply the operator.

(calc '(+ 1 (* 2 3) 4))             ⇒ 11
(calc 7)                            ⇒ 7
(calc '(max 3 (- 10 2) (min 4 9)))  ⇒ 8
(calc '(* (+ 1 1) (+ 2 2) (- 5)))   ⇒ -40
(calc '(+))                         ⇒ 0
Show answer

Evaluate every argument recursively with map calc, then apply the operator matching the symbol.

(define opFor                            ; symbol -> the real function
  (lambda (sym)
    (cond ((equal? sym '+) +)
          ((equal? sym '-) -)
          ((equal? sym '*) *)
          ((equal? sym 'max) max)
          ((equal? sym 'min) min))))

(define calc
  (lambda (E)
    (cond ((number? E) E)
          (else (apply (opFor (car E))
                       (map calc (cdr E)))))))   ; evaluate every argument first

shiftToZero

L is a non-empty list of numbers. Return the list with the smallest number subtracted from every element, so the smallest becomes 0.

The trap: writing (apply min L) inside the lambda recomputes the minimum for every element. Work it out once with let, then let the lambda use that name.

(shiftToZero '(5 3 8))   ⇒ (2 0 5)
(shiftToZero '(7))       ⇒ (0)
(shiftToZero '(-2 4 0))  ⇒ (0 6 2)
(shiftToZero '(1 1 1))   ⇒ (0 0 0)
Show answer

Work out the minimum ONCE in a let, then subtract it from every element with map.

(define shiftToZero
  (lambda (L)
    (let ((smallest (apply min L)))      ; worked out once
      (map (lambda (x) (- x smallest)) L))))

aboveMean

L is a non-empty list of numbers. Return the elements that are strictly greater than the mean (average) of L, in their original order.

(aboveMean '(1 2 3 4 10))  ⇒ (10)
(aboveMean '(2 2 2))       ⇒ ()
(aboveMean '(1 5 3 7))     ⇒ (5 7)
(aboveMean '(3 4))         ⇒ (4)
Show answer

Work out the mean once with let, then filter the elements strictly above it.

(define aboveMean
  (lambda (L)
    (let ((mean (/ (apply + L) (length L))))
      (filter (lambda (x) (> x mean)) L))))

percentOfTotal

L is a non-empty list of positive numbers. Return each element as a percentage of the total, rounded down to a whole number with quotient: the element x becomes (quotient (* 100 x) total).

(percentOfTotal '(1 1 2))  ⇒ (25 25 50)
(percentOfTotal '(5))      ⇒ (100)
(percentOfTotal '(1 2))    ⇒ (33 66)
(percentOfTotal '(3 1))    ⇒ (75 25)
Show answer

Work out the total once, then map each x to (quotient (* 100 x) total).

(define percentOfTotal
  (lambda (L)
    (let ((total (apply + L)))
      (map (lambda (x) (quotient (* 100 x) total)) L))))

minMaxRange

L is a non-empty list of numbers. Return a three-element list: the smallest number, the largest, and the range (largest minus smallest).

let* is like let, but each name can use the ones defined before it. Try let* so the range can use the names for min and max.

(minMaxRange '(4 9 2 7))  ⇒ (2 9 7)
(minMaxRange '(5))        ⇒ (5 5 0)
(minMaxRange '(-3 3))     ⇒ (-3 3 6)
(minMaxRange '(10 1 10))  ⇒ (1 10 9)
Show answer

let* lets the third value use the first two: min, max, then max − min.

(define minMaxRange
  (lambda (L)
    (let* ((lo (apply min L))
           (hi (apply max L)))
      (list lo hi (- hi lo)))))

closestTo

Return the element of the non-empty list L that is closest to the number x. If two are equally close, return the one that comes first in L.

(closestTo 5 '(1 4 9))   ⇒ 4
(closestTo 6 '(4 8))     ⇒ 4
(closestTo 0 '(-3 2 7))  ⇒ 2
(closestTo 10 '(10))     ⇒ 10
Show answer

Best-so-far using the distance abs (- x element). Replace only when an element is strictly closer.

(define closest                          ; best = closest so far
  (lambda (x best L)
    (cond ((null? L) best)
          ((< (abs (- (car L) x)) (abs (- best x)))   ; strictly closer only
           (closest x (car L) (cdr L)))
          (else (closest x best (cdr L))))))

(define closestTo
  (lambda (x L)
    (closest x (car L) (cdr L))))

tagWith

Return a list where every element x of L becomes the two-element list (tag x).

The point: the lambda you give to map takes only x, but it can still use tag, because it was written inside tagWith. That's a closure.

(tagWith 'a '(1 2 3))  ⇒ ((a 1) (a 2) (a 3))
(tagWith 'x '())       ⇒ ()
(tagWith 0 '((1) b))   ⇒ ((0 (1)) (0 b))
(tagWith 'z '(z))      ⇒ ((z z))
Show answer

The lambda passed to map can see tag because it was written inside tagWith. That's a closure.

(define tagWith
  (lambda (tag L)
    (map (lambda (x) (list tag x)) L)))

tableOf

Build a table: one row for each x in L1, and in that row, (f x y) for each y in L2.

You need two lambdas, one inside the other. The inner one uses both x (from the outer lambda) and y (its own).

(tableOf * '(1 2 3) '(1 2))  ⇒ ((1 2) (2 4) (3 6))
(tableOf list '(a) '(1 2))   ⇒ (((a 1) (a 2)))
(tableOf + '() '(1 2))       ⇒ ()
(tableOf - '(10 20) '(1))    ⇒ ((9) (19))
Show answer

Nested maps: the inner lambda sees x from the outer lambda and its own y.

(define tableOf
  (lambda (f L1 L2)
    (map (lambda (x)
           (map (lambda (y) (f x y)) L2))
         L1)))

distancesFrom

p and every element of pts are points: two-element lists (x y). Return the "city-block" (Manhattan) distance from p to each point: |x1 − x2| + |y1 − y2|.

(distancesFrom '(0 0) '((1 2) (3 -1)))    ⇒ (3 4)
(distancesFrom '(5 5) '((5 5)))           ⇒ (0)
(distancesFrom '(1 1) '())                ⇒ ()
(distancesFrom '(-1 2) '((2 2) (-1 -2)))  ⇒ (3 4)
Show answer

Map each point to |x1 − x2| + |y1 − y2|.

(define distancesFrom
  (lambda (p pts)
    (map (lambda (q)
           (+ (abs (- (car p) (car q)))
              (abs (- (cadr p) (cadr q)))))
         pts)))

stepChanges

Return how much each element changes from the one before it: for (1 4 9 16) that's (3 5 7). A list with fewer than two elements has no changes.

Trick: (cdr L) is the list without its first element; L without its last element is the other half. map over both together.

(stepChanges '(1 4 9 16))  ⇒ (3 5 7)
(stepChanges '(5))         ⇒ ()
(stepChanges '(3 1))       ⇒ (-2)
(stepChanges '(2 2 5))     ⇒ (0 3)
(stepChanges '())          ⇒ ()
Show answer

Pair each element with the one before it by mapping - over (cdr L) and L without its last element.

(define allButLast
  (lambda (L)
    (reverse (cdr (reverse L)))))

(define stepChanges
  (lambda (L)
    (cond ((or (null? L) (null? (cdr L))) '())
          (else (map - (cdr L) (allButLast L))))))   ; next minus previous

longestRowLength

LL is a non-empty list of lists. Return the length of the longest inner list. One line: turn every list into its length, then take the biggest.

(longestRowLength '((1 2) (3) (4 5 6)))  ⇒ 3
(longestRowLength '(()))                 ⇒ 0
(longestRowLength '((a) (b)))            ⇒ 1
(longestRowLength '((1 2 3 4) ()))       ⇒ 4
Show answer

Map each row to its length, then take apply max.

(define longestRowLength
  (lambda (LL)
    (apply max (map length LL))))

sumOfProducts

LL is a list of non-empty lists of numbers. Multiply the numbers in each inner list, then add up those products. ((1 2) (3 4)) gives 2 + 12 = 14.

(sumOfProducts '((1 2) (3 4)))  ⇒ 14
(sumOfProducts '((5)))          ⇒ 5
(sumOfProducts '((2 2 2) (1)))  ⇒ 9
(sumOfProducts '())             ⇒ 0
Show answer

Map each list to its product with apply *, then add those up.

(define sumOfProducts
  (lambda (LL)
    (apply + (map (lambda (L) (apply * L)) LL))))

allSameLength

Return #t if every list in LL has the same length (and #t for no lists at all), otherwise #f.

= takes any number of arguments: (= 2 2 2) is #t. So if you had all the lengths as a list…

(allSameLength '((1 2) (3 4)))  ⇒ #t
(allSameLength '((1) (2 3)))    ⇒ #f
(allSameLength '((a)))          ⇒ #t
(allSameLength '())             ⇒ #t
(allSameLength '(() () ()))     ⇒ #t
Show answer

= takes any number of arguments, so (apply = lengths) checks them all at once. No lists means #t.

(define allSameLength
  (lambda (LL)
    (cond ((null? LL) #t)                ; (=) with no arguments isn't allowed
          (else (apply = (map length LL))))))

averageLength

LL is a non-empty list of lists. Return the average length of the inner lists (it can be a decimal).

(averageLength '((1 2) (3 4 5 6)))  ⇒ 3
(averageLength '((a)))              ⇒ 1
(averageLength '((1) (2 3)))        ⇒ 1.5
(averageLength '(() (1 2 3)))       ⇒ 1.5
Show answer

Total of the lengths divided by how many lists there are.

;; In Racket/Moodle this prints 3/2 rather than 1.5 -- same number.
(define averageLength
  (lambda (LL)
    (/ (apply + (map length LL)) (length LL))))

bestRow

M is a non-empty list of non-empty rows of numbers. Return the position (counting from 0) of the row with the biggest sum. If several rows tie, return the first.

(bestRow '((1 2) (5 0) (2 2)))  ⇒ 1
(bestRow '((3)))                ⇒ 0
(bestRow '((1 1) (2 0)))        ⇒ 0
(bestRow '((0) (0) (9 1)))      ⇒ 2
Show answer

Compute each row's sum, then find the position of the first maximum.

(define posOf                            ; position of the first x in L
  (lambda (x L)
    (cond ((equal? x (car L)) 0)
          (else (+ 1 (posOf x (cdr L)))))))

(define bestRow
  (lambda (M)
    (let ((sums (map (lambda (row) (apply + row)) M)))
      (posOf (apply max sums) sums))))

meanOf

Write meanOf, which takes one or more numbers as separate arguments and returns their average (it can be a decimal).

(meanOf 2 4 6)     ⇒ 4
(meanOf 5)         ⇒ 5
(meanOf 1 2)       ⇒ 1.5
(meanOf 10 0 0 0)  ⇒ 2.5
Show answer

A variable-arity average: apply +, divided by length.

(define meanOf
  (lambda nums
    (/ (apply + nums) (length nums))))

spreadOf

Write spreadOf, which takes one or more numbers and returns the biggest minus the smallest.

(spreadOf 3 9 4)    ⇒ 6
(spreadOf 7)        ⇒ 0
(spreadOf -5 5)     ⇒ 10
(spreadOf 2 2 2 2)  ⇒ 0
Show answer

Max minus min of the arguments, with apply max and apply min.

(define spreadOf
  (lambda nums
    (- (apply max nums) (apply min nums))))

scaleAll

Write scaleAll, which takes a number k followed by any number of numbers, and returns the list of those numbers each multiplied by k.

(scaleAll 2 1 2 3)  ⇒ (2 4 6)
(scaleAll 5)        ⇒ ()
(scaleAll -1 4 -4)  ⇒ (-4 4)
(scaleAll 0 9 9)    ⇒ (0 0)
Show answer

(k . nums) names the factor, then map multiplies each number by k.

(define scaleAll
  (lambda (k . nums)
    (map (lambda (x) (* k x)) nums)))

sumLists

Write sumLists, which takes one or more lists of numbers (all the same length) and adds them element by element.

(map + L1 L2 L3) would do it for three lists. But you don't know how many lists you'll get, so you can't type them out.

(sumLists '(1 2) '(10 20) '(100 200))  ⇒ (111 222)
(sumLists '(1 2 3))                    ⇒ (1 2 3)
(sumLists '(5) '(5))                   ⇒ (10)
(sumLists '() '())                     ⇒ ()
Show answer

(apply map + lists): you don't know how many lists there are, so apply spreads them into map.

(define sumLists
  (lambda lists
    (apply map + lists)))                ; = (map + L1 L2 ...)

averageLists

Write averageLists, which takes one or more equal-length lists of numbers and returns their element-by-element average.

Like sumLists, but instead of + you pass map a lambda of your own that takes any number of arguments (one from each list) and averages them.

(averageLists '(1 2) '(3 4))               ⇒ (2 3)
(averageLists '(1 2 3) '(3 2 1) '(2 2 2))  ⇒ (2 2 2)
(averageLists '(4))                        ⇒ (4)
(averageLists '(1) '(2))                   ⇒ (1.5)
Show answer

Like sumLists, but pass map your own variable-arity averaging lambda.

(define averageLists
  (lambda lists
    (apply map
           (lambda xs (/ (apply + xs) (length xs)))   ; one number from each list
           lists)))

makeScaler

(makeScaler k) should return a function. That function takes a list of numbers and multiplies each by k.

Three lambdas: makeScaler itself, the one it returns, and the one inside map.

((makeScaler 3) '(1 2))            ⇒ (3 6)
((makeScaler 0) '(5 6 7))          ⇒ (0 0 0)
(map (makeScaler 2) '((1) (2 3)))  ⇒ ((2) (4 6))
((makeScaler -1) '())              ⇒ ()
Show answer

Three lambdas: makeScaler remembers k, the returned function takes a list, and the map lambda multiplies.

(define makeScaler
  (lambda (k)
    (lambda (L)
      (map (lambda (x) (* k x)) L))))

makeClamp

(makeClamp lo hi) returns a function of one number x that "clamps" it into the range: below lo becomes lo, above hi becomes hi, otherwise unchanged.

((makeClamp 0 10) 15)           ⇒ 10
((makeClamp 0 10) -3)           ⇒ 0
((makeClamp 0 10) 7)            ⇒ 7
(map (makeClamp 1 3) '(0 2 9))  ⇒ (1 2 3)
Show answer

Return a lambda that remembers lo and hi and clamps with a three-way cond.

(define makeClamp
  (lambda (lo hi)
    (lambda (x)
      (cond ((< x lo) lo)
            ((> x hi) hi)
            (else x)))))

twice

(twice f) returns a new function that applies f two times: ((twice f) x) is (f (f x)).

((twice (lambda (x) (* x 3))) 2)          ⇒ 18
((twice cdr) '(1 2 3))                    ⇒ (3)
((twice (twice (lambda (x) (+ x 1)))) 0)  ⇒ 4
((twice reverse) '(a b))                  ⇒ (a b)
Show answer

Return (lambda (x) (f (f x))).

(define twice
  (lambda (f)
    (lambda (x)
      (f (f x)))))

adders

For each number n in L, make a function that adds n to its argument. Return the list of those functions.

The tests can't print functions, so they call each one on 10.

(map (lambda (f) (f 10)) (adders '(1 2 3)))  ⇒ (11 12 13)
(map (lambda (f) (f 0)) (adders '(-5)))      ⇒ (-5)
(adders '())                                 ⇒ ()
((car (adders '(100 7))) 1)                  ⇒ 101
Show answer

map over the numbers, building a separate closure for each n.

(define adders
  (lambda (L)
    (map (lambda (n)
           (lambda (x) (+ x n)))         ; each function remembers its own n
         L)))

memberOf

(memberOf L) returns a predicate: a function of x that returns #t if x is in L, otherwise #f. (Careful: member returns a list, not #t.)

(filter (memberOf '(a e i o u)) '(b a d e))  ⇒ (a e)
((memberOf '()) 'x)                          ⇒ #f
((memberOf '(1 2 3)) 2)                      ⇒ #t
(filter (memberOf '(2 4)) '(1 2 3 4 4))      ⇒ (2 4 4)
Show answer

member returns a list or #f, so convert it to a clean #t or #f.

(define memberOf
  (lambda (L)
    (lambda (x)
      (if (member x L) #t #f))))

counterFor

(counterFor pred) returns a function that takes a list and counts how many elements satisfy pred.

No filter this time. Turn every element into a 1 or a 0 with map, then add them up with apply.

((counterFor even?) '(1 2 4))            ⇒ 2
((counterFor even?) '())                 ⇒ 0
((counterFor symbol?) '(a 1 b 2))        ⇒ 2
(map (counterFor odd?) '((1 3) (2) ()))  ⇒ (2 0 0)

Not allowed: filter or length.

Show answer

Map each element to 1 or 0, then apply + (filter and length are banned).

(define counterFor
  (lambda (pred)
    (lambda (L)
      (apply + (map (lambda (x) (if (pred x) 1 0)) L)))))

gradeAll

scores is a non-empty list of positive numbers. Grade each score relative to the best one:

  • A if it's at least 90% of the best
  • B if it's at least 70%
  • otherwise C

Return the list of grades as symbols. Tip: to avoid decimals, compare (* 10 s) with (* 9 best) instead of s with (* 0.9 best).

(gradeAll '(100 95 70 50))  ⇒ (A A B C)
(gradeAll '(10 9 7 6))      ⇒ (A A B C)
(gradeAll '(50))            ⇒ (A)
(gradeAll '(40 100 89 69))  ⇒ (C A B C)
Show answer

Find the best score once. Comparing 10·s with 9·best and 7·best avoids decimals.

(define gradeAll
  (lambda (scores)
    (let ((best (apply max scores)))
      (map (lambda (s)
             (cond ((>= (* 10 s) (* 9 best)) 'A)
                   ((>= (* 10 s) (* 7 best)) 'B)
                   (else 'C)))
           scores))))

countEach

For each element of keys, count how many times it appears in L. Return the counts in the same order as keys.

No filter: count with map and apply +, like counterFor.

(countEach '(a b c) '(a b a a))    ⇒ (3 1 0)
(countEach '() '(1 2))             ⇒ ()
(countEach '(1 2) '())             ⇒ (0 0)
(countEach '((x) y) '((x) y (x)))  ⇒ (2 1)

Not allowed: filter or length.

Show answer

For each key, count it in L by mapping to 1/0 and adding.

(define countEach
  (lambda (keys L)
    (map (lambda (k)
           (apply + (map (lambda (x) (if (equal? x k) 1 0)) L)))
         keys)))

topScorer

names and scores are lists of the same length: the score of the first name is the first score, and so on. Return the name with the highest score (the first one, if several tie).

(topScorer '(ann bob cy) '(70 92 85))  ⇒ bob
(topScorer '(solo) '(1))               ⇒ solo
(topScorer '(a b c) '(5 9 9))          ⇒ b
(topScorer '(x y) '(-1 -2))            ⇒ x
Show answer

Find the highest score, then walk names and scores together to the first name with that score.

(define nameWith                         ; first name whose score is s
  (lambda (s names scores)
    (cond ((= (car scores) s) (car names))
          (else (nameWith s (cdr names) (cdr scores))))))

(define topScorer
  (lambda (names scores)
    (nameWith (apply max scores) names scores)))

polyEval

coeffs is (c0 c1 c2 ...), standing for the polynomial c0 + c1·x + c2·x² + … Return its value at x.

You need each coefficient paired with its power (0 1 2 ...). Build that list of powers first, then map over both lists at once.

(polyEval '(1 2 3) 2)   ⇒ 17
(polyEval '(5) 9)       ⇒ 5
(polyEval '(0 0 1) -3)  ⇒ 9
(polyEval '() 4)        ⇒ 0
Show answer

Build the powers (0 1 2 …), then add up c × x^p with a two-list map.

(define countUp                          ; (i i+1 ... n-1)
  (lambda (i n)
    (cond ((= i n) '())
          (else (cons i (countUp (+ i 1) n))))))

(define polyEval
  (lambda (coeffs x)
    (let ((powers (countUp 0 (length coeffs))))
      (apply + (map (lambda (c p) (* c (expt x p)))
                    coeffs powers)))))

rowsMinusMin

M is a list of non-empty rows of numbers. From every row, subtract that row's own minimum, so each row's smallest becomes 0.

This is shiftToZero done to every row: the let now goes inside the lambda, so each row works out its own minimum.

(rowsMinusMin '((3 5 4) (10 7)))  ⇒ ((0 2 1) (3 0))
(rowsMinusMin '())                ⇒ ()
(rowsMinusMin '((1) (2 2)))       ⇒ ((0) (0 0))
(rowsMinusMin '((-1 -5 0)))       ⇒ ((4 0 5))
Show answer

shiftToZero for every row: the let sits inside the lambda, so each row uses its own minimum.

(define rowsMinusMin
  (lambda (M)
    (map (lambda (row)
           (let ((smallest (apply min row)))    ; each row's own minimum
             (map (lambda (x) (- x smallest)) row)))
         M)))

Scope and closures

makeMultiplier

Write makeMultiplier, which takes a number N and returns a function. That function takes a number and multiplies it by N.

((makeMultiplier 3) 5) gives 15.

This is a closure: the function you return remembers the N it was made with, even after makeMultiplier has finished running.

((makeMultiplier 3) 5)
  ⇒ 15
(map (makeMultiplier 2) '(1 2 3))
  ⇒ (2 4 6)
((makeMultiplier 0) 99)
  ⇒ 0
(let ((triple (makeMultiplier 3)) (double (makeMultiplier 2))) (list (triple 10) (double 10)))
  ⇒ (30 20)

Not allowed: curry or curryr.

Show answer

A closure: the returned lambda remembers N and multiplies its argument by it.

(define makeMultiplier
  (lambda (N)
    (lambda (x)
      (* x N))))

predictShadow

Don't run this code. Read it and work out the answer by hand.

(define x 10)
(define f (lambda (x) (+ x 1)))
(define g (lambda (y) (+ x y)))
(define h (lambda (x) (g x)))

What does (list (f 5) (g 5) (h 5) x) give? Define predictShadow to be your answer, e.g. (define predictShadow '(1 2 3 4)).

(list-ref predictShadow 0)  ⇒ 6
(list-ref predictShadow 1)  ⇒ 15
(list-ref predictShadow 2)  ⇒ 15
(list-ref predictShadow 3)  ⇒ 10
Show answer

Lexical scope: a function sees the variables where it was WRITTEN, not where it's called from. g was written at top level, so its x is always the global 10, even when h calls it with a local x.

;; (f 5): f's own x is 5, so 6.
;; (g 5): g has no x of its own, so it uses the global x = 10: 10 + 5 = 15.
;; (h 5): h's x is 5, but g was DEFINED at top level, so inside g, x is still
;;        the global 10 (lexical scope): (g 5) = 15.
;; x:     the global x was never changed: 10.
(define predictShadow '(6 15 15 10))

makeGreaterThan

Write makeGreaterThan, which takes a number N and returns a test: a function that takes one number and returns #t if it's bigger than N, #f otherwise.

Then (filter (makeGreaterThan 3) '(1 5 2 7)) gives (5 7).

(filter (makeGreaterThan 3) '(1 5 2 7))  ⇒ (5 7)
((makeGreaterThan 10) 10)                ⇒ #f
((makeGreaterThan 10) 11)                ⇒ #t
(map (makeGreaterThan 0) '(-1 0 1))      ⇒ (#f #f #t)
Show answer

Return a test that remembers N and compares with >.

(define makeGreaterThan
  (lambda (N)
    (lambda (x)
      (> x N))))

predictLexical

Don't run this code. Work it out by hand.

(define n 1)
(define getN (lambda () n))
(define test (lambda (n) (getN)))
(define test2
  (lambda (n)
    (let ((getN (lambda () n)))
      (getN))))

What does this give?

(list (test 100)
      (let ((n 5)) (getN))
      (let ((n 5)) n)
      (test2 100))

Define predictLexical to be your answer (a list of four values).

(list-ref predictLexical 0)  ⇒ 1
(list-ref predictLexical 1)  ⇒ 1
(list-ref predictLexical 2)  ⇒ 5
(list-ref predictLexical 3)  ⇒ 100
Show answer

getN was defined at top level, so it always sees the global n = 1, whatever local n exists where it's called. Only the getN created INSIDE test2 sees test2's n.

;; (test 100):        getN was defined at top level, so it sees the global n = 1.
;; (let ((n 5)) (getN)): same reason, still 1. A local n doesn't reach into getN.
;; (let ((n 5)) n):   here n is used directly inside the let: 5.
;; (test2 100):       this getN is made INSIDE test2, so it sees test2's n = 100.
(define predictLexical '(1 1 5 100))

compose2

Write compose2, which takes two one-argument functions F and G and returns a new function that does G first, then F:

((compose2 F G) x) means (F (G x)).

((compose2 car cdr) '(1 2 3))                             ⇒ 2
((compose2 (lambda (x) (* x x)) (lambda (x) (+ x 1))) 4)  ⇒ 25
((compose2 length cdr) '(a b c))                          ⇒ 2
(map (compose2 car reverse) '((1 2) (3 4 5)))             ⇒ (2 5)

Not allowed: compose or compose1.

Show answer

Return (lambda (x) (F (G x))): G runs first.

(define compose2
  (lambda (F G)
    (lambda (x)
      (F (G x)))))

flip

Write flip, which takes a two-argument function F and returns a new two-argument function that calls F with its arguments swapped:

((flip -) 1 10) means (- 10 1), which is 9.

((flip -) 1 10)         ⇒ 9
((flip cons) '(2 3) 1)  ⇒ (1 2 3)
((flip list) 'a 'b)     ⇒ (b a)
((flip expt) 2 3)       ⇒ 9
Show answer

Return a two-argument lambda that calls F with the arguments swapped.

(define flip
  (lambda (F)
    (lambda (a b)
      (F b a))))

makeCounter

Write makeCounter, which takes no arguments and returns a counter function. Each time you call the counter it returns the next number: 1, then 2, then 3…

Two different counters must count separately.

You need set!, which changes the value of a variable that already exists: (set! n (+ n 1)). Inside a lambda, you can do set! first and then give the answer, one after the other: (lambda () (set! …) n).

((makeCounter))
  ⇒ 1
(let ((c (makeCounter))) (c) (c) (c))
  ⇒ 3
(let ((a (makeCounter)) (b (makeCounter))) (a) (a) (b) (list (a) (b)))
  ⇒ (3 2)
Show answer

The let inside makeCounter creates a fresh n for every counter. set! updates it, then n is returned.

(define makeCounter
  (lambda ()
    (let ((n 0))                         ; a new n for every counter made
      (lambda ()
        (set! n (+ n 1))
        n))))

makeAccumulator

Write makeAccumulator, which takes a starting number and returns a function. That function takes a number, adds it to the running total, and returns the new total.

(define acc (makeAccumulator 100))
(acc 10) ; 110
(acc 10) ; 120
((makeAccumulator 100) 10)
  ⇒ 110
(let ((a (makeAccumulator 100))) (a 10) (a 10))
  ⇒ 120
(let ((a (makeAccumulator 0)) (b (makeAccumulator 50))) (a 5) (b 5) (list (a 1) (b 1)))
  ⇒ (6 56)
(let ((a (makeAccumulator 10))) (a -10))
  ⇒ 0
Show answer

The parameter itself works as the remembered state: set! it and return it.

(define makeAccumulator
  (lambda (total)                        ; the parameter itself is the running total
    (lambda (x)
      (set! total (+ total x))
      total)))

makeIterator

Write makeIterator, which takes a list and returns a function of no arguments. Each call returns the next element of the list. Once the list is used up, every call returns the symbol done.

((makeIterator '(a b)))
  ⇒ a
(let ((it (makeIterator '(a b)))) (it) (it))
  ⇒ b
(let ((it (makeIterator '(a b)))) (it) (it) (it))
  ⇒ done
(let ((it (makeIterator '()))) (list (it) (it)))
  ⇒ (done done)
(let ((i (makeIterator '(1 2 3))) (j (makeIterator '(1 2 3)))) (i) (i) (list (i) (j)))
  ⇒ (3 1)
Show answer

Remember the remaining list. Each call returns its car and set!s it to its cdr; an empty list gives done.

(define makeIterator
  (lambda (L)
    (lambda ()
      (cond ((null? L) 'done)
            (else (let ((x (car L)))
                    (set! L (cdr L))     ; move along for next time
                    x))))))

predictShared

Don't run this code. Work it out by hand, call by call.

(define makeCounter2
  (let ((total 0))
    (lambda ()
      (let ((mine 0))
        (lambda ()
          (set! total (+ total 1))
          (set! mine (+ mine 1))
          (list mine total))))))
(define a (makeCounter2))
(define b (makeCounter2))

Then these calls happen, in this order: (a), (a), (b), (b).

What does the last call (b) return? Define predictShared to be your answer, a list of two numbers.

(car predictShared)   ⇒ 2
(cadr predictShared)  ⇒ 4
Show answer

total is created ONCE, because the let is outside the inner lambda, so a and b share it. mine is created per counter. So the calls give (1 1), (2 2), (1 3), (2 4).

;; total is created ONCE (the let is outside the lambda), so a and b share it.
;; mine is created each time makeCounter2 is called, so a and b each have their own.
;; (a) -> (1 1), (a) -> (2 2), (b) -> (1 3), (b) -> (2 4)
(define predictShared '(2 4))

makeStack

Write makeStack, which returns a stack object. The stack is a function that takes a message (a symbol) and, for push, one more argument:

  • (s 'push X) puts X on top and returns the new size
  • (s 'pop) removes the top element and returns it, or returns empty if there's nothing there
  • (s 'peek) returns the top element without removing it, or empty
  • (s 'size) returns how many elements there are

Each stack has its own contents.

(let ((s (makeStack))) (s 'push 7))
  ⇒ 1
(let ((s (makeStack))) (s 'push 1) (s 'push 2) (s 'pop))
  ⇒ 2
(let ((s (makeStack))) (s 'push 1) (s 'push 2) (s 'pop) (s 'peek))
  ⇒ 1
(let ((s (makeStack))) (s 'pop))
  ⇒ empty
(let ((s (makeStack))) (s 'push 'a) (s 'push 'b) (s 'peek) (s 'size))
  ⇒ 2
(let ((s (makeStack)) (t (makeStack))) (s 'push 1) (t 'size))
  ⇒ 0
Show answer

Message passing: the stack is a lambda over a private list, using cond on the message. push conses onto the front, and pop returns the front and set!s the list to its rest.

(define makeStack
  (lambda ()
    (let ((items '()))                   ; top of the stack is the car
      (lambda args                       ; (msg) or (msg X)
        (let ((msg (car args)))
          (cond ((equal? msg 'push)
                 (set! items (cons (cadr args) items))
                 (length items))
                ((equal? msg 'pop)
                 (cond ((null? items) 'empty)
                       (else (let ((top (car items)))
                               (set! items (cdr items))
                               top))))
                ((equal? msg 'peek)
                 (cond ((null? items) 'empty)
                       (else (car items))))
                ((equal? msg 'size) (length items))))))))

memoize

Write memoize, which takes a one-argument function F and returns a new function that gives the same answers as F, but remembers them. The first time it's called with some input it calls F and stores the answer. After that, the same input returns the stored answer without calling F again.

Store the answers in an association list, like ((4 16) (5 25)). (assoc 4 table) returns the pair for 4, or #f if there isn't one.

((memoize (lambda (x) (* x x))) 9)
  ⇒ 81
(let* ((calls 0) (sq (lambda (x) (set! calls (+ calls 1)) (* x x))) (m (memoize sq))) (m 4) (m 4) (m 5) (m 4) (list (m 5) calls))
  ⇒ (25 2)
(let* ((m1 (memoize (lambda (x) (+ x 1)))) (m2 (memoize (lambda (x) (* x 10))))) (m1 3) (list (m1 3) (m2 3)))
  ⇒ (4 30)
Show answer

Keep a private association list of (input answer). Check it with assoc before calling F, and store each new answer.

(define memoize
  (lambda (F)
    (let ((table '()))                   ; ((input answer) ...)
      (lambda (x)
        (let ((found (assoc x table)))
          (cond (found (cadr found))     ; seen before: reuse it
                (else (let ((answer (F x)))
                        (set! table (cons (list x answer) table))
                        answer))))))))

From the lectures

hailstone

The Collatz rule: if n is even, the next number is n/2; if n is odd, it's 3n+1. Starting from any positive n, you keep going until you reach 1.

Write hailstone, which returns the whole sequence from n down to 1.

(hailstone 6) gives (6 3 10 5 16 8 4 2 1).

(hailstone 1)  ⇒ (1)
(hailstone 4)  ⇒ (4 2 1)
(hailstone 6)  ⇒ (6 3 10 5 16 8 4 2 1)
(hailstone 3)  ⇒ (3 10 5 16 8 4 2 1)
Show answer

Apply the Collatz step and cons each number on. The base case 1 gives (1).

(define nextHail
  (lambda (n)
    (cond ((even? n) (quotient n 2))
          (else (+ (* 3 n) 1)))))

(define hailstone
  (lambda (n)
    (cond ((= n 1) '(1))
          (else (cons n (hailstone (nextHail n)))))))

hailLength

Write hailLength, which returns how many numbers are in the hailstone sequence for n, without building the list (length is switched off).

(hailLength 6) is 9, because (6 3 10 5 16 8 4 2 1) has 9 numbers.

(hailLength 1)   ⇒ 1
(hailLength 4)   ⇒ 3
(hailLength 6)   ⇒ 9
(hailLength 27)  ⇒ 112

Not allowed: length.

Show answer

The same recursion as hailstone, but count 1 per step instead of building the list.

(define nextHail
  (lambda (n)
    (cond ((even? n) (quotient n 2))
          (else (+ (* 3 n) 1)))))

(define hailLength
  (lambda (n)
    (cond ((= n 1) 1)
          (else (+ 1 (hailLength (nextHail n)))))))

longestHail

Write longestHail, which returns the number n with lo ≤ n ≤ hi that has the longest hailstone sequence. If several share the longest, return the smallest of them.

You'll need your hailLength from the last problem: define it again in this file.

(longestHail 1 10)   ⇒ 9
(longestHail 5 5)    ⇒ 5
(longestHail 1 4)    ⇒ 3
(longestHail 12 13)  ⇒ 12
(longestHail 1 30)   ⇒ 27
Show answer

Best-so-far over n from lo to hi. Replace only on a strictly longer sequence, so the smallest n wins ties.

(define nextHail
  (lambda (n)
    (cond ((even? n) (quotient n 2))
          (else (+ (* 3 n) 1)))))

(define hailLength
  (lambda (n)
    (cond ((= n 1) 1)
          (else (+ 1 (hailLength (nextHail n)))))))

;; best = best n so far; check n, n+1, ..., hi
(define bestFrom
  (lambda (best n hi)
    (cond ((> n hi) best)
          ((> (hailLength n) (hailLength best))    ; strictly longer, so ties keep the smaller
           (bestFrom n (+ n 1) hi))
          (else (bestFrom best (+ n 1) hi)))))

(define longestHail
  (lambda (lo hi)
    (bestFrom lo (+ lo 1) hi)))

hanoi

Tower of Hanoi: move N disks from tower from to tower to, using via as the spare. You can only move one disk at a time, and a bigger disk can never sit on a smaller one.

Write hanoi, which returns the list of moves. Each move is a two-element list (source target).

(hanoi 2 'a 'b 'c) gives ((a b) (a c) (b c)).

(hanoi 0 'a 'b 'c)           ⇒ ()
(hanoi 1 'a 'b 'c)           ⇒ ((a c))
(hanoi 2 'a 'b 'c)           ⇒ ((a b) (a c) (b c))
(hanoi 3 'a 'b 'c)           ⇒ ((a c) (a b) (c b) (a c) (b a) (b c) (a c))
(length (hanoi 5 'x 'y 'z))  ⇒ 31
Show answer

Move N−1 disks out of the way onto the spare tower, move the biggest disk, then move the N−1 back on top. Zero disks need no moves.

;; argument order is (hanoi N from via to)
(define hanoi
  (lambda (N from via to)
    (cond ((= N 0) '())
          (else (append (hanoi (- N 1) from to via)   ; move N-1 out of the way
                        (list (list from to))         ; move the biggest disk
                        (hanoi (- N 1) via from to))))))  ; put the N-1 back on top

hanoiMoves

Write hanoiMoves, which returns how many moves (hanoi N …) makes, without building the list of moves (and without expt).

(hanoiMoves 0)   ⇒ 0
(hanoiMoves 1)   ⇒ 1
(hanoiMoves 3)   ⇒ 7
(hanoiMoves 10)  ⇒ 1023

Not allowed: expt, length or arithmetic-shift.

Show answer

The same structure counted: moves(N) = 2·moves(N−1) + 1, with moves(0) = 0.

;; same shape as hanoi: two smaller towers plus one move
(define hanoiMoves
  (lambda (N)
    (cond ((= N 0) 0)
          (else (+ 1 (* 2 (hanoiMoves (- N 1))))))))

checkSolution

In the countdown problem, an answer is an expression like (* (+ 1 2) 8), stored as a list. Write checkSolution, which returns #t if the expression E works out to the target T, and #f otherwise.

(On Moodle, eval may be called primitive-eval.)

(checkSolution 24 '(* (+ 1 2) 8))  ⇒ #t
(checkSolution 24 '(* 4 (+ 5 1)))  ⇒ #t
(checkSolution 10 '(- 20 5))       ⇒ #f
(checkSolution 7 7)                ⇒ #t

Not allowed: apply.

Show answer

The expression is just data, so eval it and compare the result with the target.

(define checkSolution
  (lambda (T E)
    (= (eval E) T)))

usesOnly

A countdown answer may use each number in L at most once (and may skip some). Write usesOnly, which returns #t if every number in the expression E comes from L, respecting how many times it appears there.

E is either a number or a list (op left right).

(usesOnly '(* (+ 1 2) 8) '(1 2 4 5 8))      ⇒ #t
(usesOnly '(+ 2 2) '(1 2 4))                ⇒ #f
(usesOnly '(+ 2 2) '(2 2))                  ⇒ #t
(usesOnly 5 '(5))                           ⇒ #t
(usesOnly '(* 3 3) '(1 2 4))                ⇒ #f
(usesOnly '(- (* 4 5) (+ 1 8)) '(8 5 4 1))  ⇒ #t

Not allowed: flatten or remove*.

Show answer

Collect every number the expression uses, then cross each one off a copy of L. Running out means a number was used too often.

;; every number used in E, in order
(define numbersIn
  (lambda (E)
    (cond ((number? E) (list E))
          (else (append (numbersIn (cadr E)) (numbersIn (caddr E)))))))

(define removeOne                        ; L with the first x taken out
  (lambda (x L)
    (cond ((null? L) '())
          ((equal? x (car L)) (cdr L))
          (else (cons (car L) (removeOne x (cdr L)))))))

(define allAvailable                     ; can every number in used be taken from L?
  (lambda (used L)
    (cond ((null? used) #t)
          ((member (car used) L)
           (allAvailable (cdr used) (removeOne (car used) L)))   ; use it up
          (else #f))))

(define usesOnly
  (lambda (E L)
    (allAvailable (numbersIn E) L)))

countdownPM

Write countdownPM, which finds an expression equal to the target T using numbers from L, each at most once, with only + and −. Return the expression as a list (or a bare number if one number from L already equals T). If there's no way, return '().

Any correct expression is accepted: the tests check your answer with eval. This is the version from the countdown lecture notes, so make sure it also handles the case the lecture's first version missed, (countdownPM 28 '(29 1)).

(let ((e (countdownPM 5 '(1 5 9)))) (= (eval e) 5))
  ⇒ #t
(let ((e (countdownPM 6 '(1 2 4 5)))) (= (eval e) 6))
  ⇒ #t
(let ((e (countdownPM 28 '(29 1)))) (= (eval e) 28))
  ⇒ #t
(let ((e (countdownPM 7 '(3 4 10)))) (and (= (eval e) 7) (not (equal? e 7))))
  ⇒ #t
(countdownPM 100 '(1 2 3))
  ⇒ ()
(countdownPM 4 '(2))
  ⇒ ()
Show answer

Search a pool of (value expression) items. Either an item already hits the target, or you combine any two items with + or − and search the smaller pool. Combining ANY pair (not only front ones) is what finds (- 29 1).

;; Idea: keep a pool of (value expression) items. Either something in the
;; pool already hits T, or pick two items, combine them, and search again
;; with the smaller pool. This tries every bracketing, so 29 - 1 is found.

(define removeOne
  (lambda (x L)
    (cond ((null? L) '())
          ((equal? x (car L)) (cdr L))
          (else (cons (car L) (removeOne x (cdr L)))))))

(define findHit                          ; expression of an item worth T, or #f
  (lambda (T pool)
    (cond ((null? pool) #f)
          ((= (car (car pool)) T) (cadr (car pool)))
          (else (findHit T (cdr pool))))))

(define pickTwo                          ; every (a b others) from the pool
  (lambda (pool)
    (cond ((null? pool) '())
          (else (append
                 (map (lambda (b) (list (car pool) b (removeOne b (cdr pool))))
                      (cdr pool))
                 (map (lambda (t) (list (car t) (cadr t) (cons (car pool) (caddr t))))
                      (pickTwo (cdr pool))))))))

(define combine                          ; + and - only
  (lambda (a b)
    (list (list (+ (car a) (car b)) (list '+ (cadr a) (cadr b)))
          (list (- (car a) (car b)) (list '- (cadr a) (cadr b)))
          (list (- (car b) (car a)) (list '- (cadr b) (cadr a))))))

(define firstFound                       ; first non-#f result of f over L
  (lambda (f L)
    (cond ((null? L) #f)
          (else (let ((r (f (car L))))
                  (if r r (firstFound f (cdr L))))))))

(define search
  (lambda (T pool)
    (let ((hit (findHit T pool)))
      (if hit
          hit
          (firstFound (lambda (pick)
                        (firstFound (lambda (c) (search T (cons c (caddr pick))))
                                    (combine (car pick) (cadr pick))))
                      (pickTwo pool))))))

(define countdownPM
  (lambda (T L)
    (let ((answer (search T (map (lambda (n) (list n n)) L))))
      (if answer answer '()))))

countdown

Write countdown, which finds an expression equal to T using numbers from L, each at most once, with +, − and *, and any bracketing. Return the expression (or a bare number), or '() if it can't be done.

The lecture's countdown 3 notes show why the simple approach fails on (countdown 24 '(1 2 3 5)), whose answer needs (* (+ 1 2) (+ 3 5)). Taking numbers off the front one at a time can never build that.

(let ((e (countdown 24 '(1 2 3 5)))) (= (eval e) 24))  ⇒ #t
(let ((e (countdown 28 '(29 1)))) (= (eval e) 28))     ⇒ #t
(let ((e (countdown 9 '(2 3 5)))) (= (eval e) 9))      ⇒ #t
(let ((e (countdown 25 '(1 2 3 4)))) (= (eval e) 25))  ⇒ #t
(countdown 1000 '(1 2 3))                              ⇒ ()
(countdown 25 '(5))                                    ⇒ ()
Show answer

The same pool search with * added. Combining any two items, including results of earlier combinations, builds bracketings like (* (+ 1 2) (+ 3 5)).

;; Same pool search as countdownPM, plus *. Combining ANY two items
;; (not just the front ones) is what builds (* (+ 1 2) (+ 3 5)).

(define removeOne
  (lambda (x L)
    (cond ((null? L) '())
          ((equal? x (car L)) (cdr L))
          (else (cons (car L) (removeOne x (cdr L)))))))

(define findHit
  (lambda (T pool)
    (cond ((null? pool) #f)
          ((= (car (car pool)) T) (cadr (car pool)))
          (else (findHit T (cdr pool))))))

(define pickTwo
  (lambda (pool)
    (cond ((null? pool) '())
          (else (append
                 (map (lambda (b) (list (car pool) b (removeOne b (cdr pool))))
                      (cdr pool))
                 (map (lambda (t) (list (car t) (cadr t) (cons (car pool) (caddr t))))
                      (pickTwo (cdr pool))))))))

(define combine
  (lambda (a b)
    (list (list (+ (car a) (car b)) (list '+ (cadr a) (cadr b)))
          (list (- (car a) (car b)) (list '- (cadr a) (cadr b)))
          (list (- (car b) (car a)) (list '- (cadr b) (cadr a)))
          (list (* (car a) (car b)) (list '* (cadr a) (cadr b))))))

(define firstFound
  (lambda (f L)
    (cond ((null? L) #f)
          (else (let ((r (f (car L))))
                  (if r r (firstFound f (cdr L))))))))

(define search
  (lambda (T pool)
    (let ((hit (findHit T pool)))
      (if hit
          hit
          (firstFound (lambda (pick)
                        (firstFound (lambda (c) (search T (cons c (caddr pick))))
                                    (combine (car pick) (cadr pick))))
                      (pickTwo pool))))))

(define countdown
  (lambda (T L)
    (let ((answer (search T (map (lambda (n) (list n n)) L))))
      (if answer answer '()))))