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.
(defineaddAnA(lambda(X)(cons'a X)))(defineduplicate(lambda(X)(cons(car X) X)));; even numbers go down by 1, odd numbers go up by 1(definewhatIsThis(lambda(N)(cond((even? N)(- N 1))(else(+ N 1)))))
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.)
(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)).
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.)
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(defineaverage(lambda args
(/(apply+ args)(length args))))
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.)
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.
(definepower(lambda args
(cond((null? args)1)(else(expt(car args)(apply power (cdr args)))))))
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.
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:
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)))'(42326101))⇒(3141592)(map(byParity (lambda(x)(* x 10))-)'(123))⇒(-120-3)((byParity listsqrt)9)⇒3((byParity listsqrt)4)⇒(4)(map(byParity carcdr)'())⇒()(let((f (byParity (lambda(x)(quotient x 2))(lambda(x)(+(*3 x)1)))))(list(f 6)(f 3)(f (f 3))))⇒(3105)
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.
(definebyParity(lambda(forEven forOdd)(lambda(n); the closure remembers forEven and forOdd(cond((even? n)(forEven n))(else(forOdd n))))))
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))
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.
(defineprefixWith(lambda things ; things is a list of every argument(lambda(L)(append things L))))
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)'((12)))⇒((12))(map(copier 4)'((1)(9)))⇒((1111)(9999))(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(definerepeat(lambda(x k)(cond((= k 0)'())(else(cons x (repeat x (- k 1)))))))(definecopier(lambda(n)(lambda(L); remembers n(repeat (car L) n))))
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)-35-4)⇒4((averageWith (lambda(x) x))345)⇒4((averageWith (lambda(x)(* x x)))13)⇒5((averageWith length)'(a)'(b c d))⇒2((averageWith abs)-7)⇒7(let((avgSq (averageWith (lambda(x)(* x x)))))(list(avgSq 2)(avgSq 24)))⇒(410)
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.
(defineaverageWith(lambda(f)(lambda args ; any number of arguments(/(apply+(map f args))(length args)))))
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:
(definecoin(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 12))⇒#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.
(definechooser(lambda things
(lambda(); random is called inside, so every call picks fresh(list-ref things (random(length things))))))
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?)1524638)⇒(43)((tally negative?)1-5-24)⇒(22)((tally even?))⇒(00)((tally null?)'()'(a)'())⇒(21)(let((t (tally symbol?)))(list(t 'a 1'b)(t 2)))⇒((21)(01))
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.
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.
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)).
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
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)))
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.
(definefoldArgs(lambda(op start)(definecombine; named so it can call itself(lambda args
(cond((null? args) start)(else(op (car args)(apply combine (cdr args)))))))
combine))
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.
(definet(runningTally even?))(t 123); (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).
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.
(definerunningTally(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))))))
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'(124))⇒0(countOf 'x '())⇒0(countOf '(12)'((12)3(12)))⇒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.
(definecountOf(lambda(X L)(cond((null? L)0)((equal? X (car L))(+1(countOf X (cdr L))))(else(countOf X (cdr L))))))
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.
Write replaceAll, which returns L with every Old replaced by New.
(replaceAll 'a 'z '(a b a))⇒(z b z)(replaceAll 10'(1213))⇒(0203)(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.
(definereplaceAll(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)))))))
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 '(1234))⇒(13)(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.
(defineeveryOther(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
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 10'(23))⇒(23)(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.
(defineinsertAfter(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)))))))
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(12) 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.
Write indexOf, which returns the position (counting from 0) of the firstX 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.
(defineindexOf(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"
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 =.
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.
(definelistEqual(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))))
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.
(definelastIndexOf(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)))))))
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.
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.
(definemergeSorted(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)))))))
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 '(111))⇒(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.
(definecompress(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)))))))
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).
(defineelementAfter(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))))))
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 '(111))⇒1(countRuns '(1212))⇒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.
(definecountRuns(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
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 '(12)'(12))⇒-1(firstDifference '(12)'(123))⇒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.
(definefirstDifference(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)))))))
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)'(123))⇒ 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.
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.
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.
(definerevHelp; acc = what's been reversed so far(lambda(L acc)(cond((null? L) acc)(else(revHelp (cdr L)(cons(car L) acc))))))(definerevAcc(lambda(L)(revHelp L '())))
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.
(definetoNum; acc = number built so far(lambda(L acc)(cond((null? L) acc)(else(toNum (cdr L)(+(*10 acc)(car L)))))))(definedigitsToNumber(lambda(L)(toNum L 0)))
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'(123))⇒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.
(definedeepCount(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))))))
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 '(123))⇒1(longestRun '())⇒0(longestRun '(x x x))⇒3(longestRun '(112111))⇒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.
(definerunLength; length of the run at the front(lambda(L)(cond((null?(cdr L))1)((equal?(car L)(cadr L))(+1(runLength (cdr L))))(else1))))(defineafterRun; what's left after the front run(lambda(L)(cond((null?(cdr L))'())((equal?(car L)(cadr L))(afterRun (cdr L)))(else(cdr L)))))(definelongestRun(lambda(L)(cond((null? L)0)(else(max(runLength L)(longestRun (afterRun L)))))))
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 '(123))⇒(123)(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.
(defineisIn(lambda(X L)(cond((null? L)#f)((equal? X (car L))#t)(else(isIn X (cdr L))))))(definededup(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)))))))
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 (12))(x 5)))⇒(12)(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.
(definelookup(lambda(K AL)(cond((null? AL)#f)((equal? K (car(car AL)))(cadr(car AL)))(else(lookup K (cdr AL))))))
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.
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 - ...(definealternateSum(lambda(L)(cond((null? L)0)(else(-(car L)(alternateSum (cdr L)))))))
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 '(1234))⇒((12)(34))(pairUp '(a b c))⇒((a b)(c))(pairUp '())⇒()(pairUp '(x))⇒((x))(pairUp '((1)23(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.
(definepairUp(lambda(L)(cond((null? L)'())((null?(cdr L))(list L)); one left over(else(cons(list(car L)(cadr L))(pairUp (cddr L)))))))
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.
Carry the running total as an extra argument. Each step adds the next number, outputs the new total, and passes it on.
(definerunningFrom; total = sum of everything before L(lambda(L total)(cond((null? L)'())(else(let((t (+ total (car L))))(cons t (runningFrom (cdr L) t)))))))(definecumulative(lambda(L)(runningFrom L 0)))
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 '(1234)'(24))⇒(13)(listDiff '(a b a c)'(a))⇒(b c)(listDiff '()'(1))⇒()(listDiff '(x y)'())⇒(x y)(listDiff '((12)3)'((12)))⇒(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?.
(defineisIn(lambda(X L)(cond((null? L)#f)((equal? X (car L))#t)(else(isIn X (cdr L))))))(definelistDiff(lambda(A B)(cond((null? A)'())((isIn (car A) B)(listDiff (cdr A) B))(else(cons(car A)(listDiff (cdr A) B))))))
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 '(123))⇒#f(isPalindrome '())⇒#t(isPalindrome '(x))⇒#t(isPalindrome '(1221))⇒#t(isPalindrome '((12)3(12)))⇒#t
Not allowed: reverse or foldl.
Show answer
Reverse the list with an accumulator helper (reverse is banned) and compare with equal?.
(definerevHelp(lambda(L acc)(cond((null? L) acc)(else(revHelp (cdr L)(cons(car L) acc))))))(defineisPalindrome(lambda(L)(equal? L (revHelp L '()))))
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'(12))⇒(()(12))(splitAt 5'(12))⇒((12)())(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.
(definesplitAt(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)))))))
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.
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 '((12)3(4(5))))⇒(1234(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.
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.
(definebiggestIn; a number, or the deepMax of a list(lambda(x)(if(list? x)(deepMax x) x)))(definedeepMax(lambda(L)(cond((null?(cdr L))(biggestIn (car L)))(else(max(biggestIn (car L))(deepMax (cdr L)))))))
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.
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).
(defineupdateKey(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)))))))
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'(12345))⇒((12)(34)(5))(chunk 3'(a b c d e f))⇒((a b c)(d e f))(chunk 1'(x y))⇒((x)(y))(chunk 4'(12))⇒((12))(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.
(definefirstN(lambda(n L)(cond((or(= n 0)(null? L))'())(else(cons(car L)(firstN (- n 1)(cdr L)))))))(defineskipN(lambda(n L)(cond((or(= n 0)(null? L)) L)(else(skipN (- n 1)(cdr L))))))(definechunk(lambda(N L)(cond((null? L)'())(else(cons(firstN N L)(chunk N (skipN N L)))))))
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.
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(defineaddTo(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))))))(definebuild(lambda(AL table)(cond((null? AL) table)(else(build (cdr AL)(addTo table (car(car AL))(cadr(car AL))))))))(definesumByKey(lambda(AL)(build AL '())))
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(34))5))⇒(12345)(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.
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 '(111))⇒((13))
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.
(definebump; 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))))))(definecountAll(lambda(L table)(cond((null? L) table)(else(countAll (cdr L)(bump table (car L)))))))(definefrequencies(lambda(L)(countAll L '())))
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'(12))⇒(12)(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.
(defineremoveDeep(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)))))))
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 '().
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'(123))⇒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))'()'(12))⇒(24)
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))).
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.
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.
(definebestOf; 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))))))(definemaxBy(lambda(F L)(bestOf F (car L)(cdr L))))
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.
(definefindFirst; 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))))))(defineremoveOne(lambda(x L)(cond((null? L)'())((equal? x (car L))(cdr L))(else(cons(car L)(removeOne x (cdr L)))))))(defineselectionSortBy(lambda(C L)(cond((null? L)'())(else(let((best (findFirst C (car L)(cdr L))))(cons best (selectionSortBy C (removeOne best L))))))))
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?'(2456))⇒(24)(takeWhile odd?'(23))⇒()(takeWhile even?'())⇒()(takeWhile (lambda(X)(< X 10))'(159))⇒(159)(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.
(definetakeWhile(lambda(P L)(cond((null? L)'())((P (car L))(cons(car L)(takeWhile P (cdr L))))(else'())))); first failure: stop completely
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?'(2456))⇒(56)(dropWhile odd?'(23))⇒(23)(dropWhile even?'())⇒()(dropWhile (lambda(X)(< X 10))'(159))⇒()(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.
(definedropWhile(lambda(P L)(cond((null? L)'())((P (car L))(dropWhile P (cdr L)))(else L))))
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))'(14916))⇒(357)(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 '().
(defineadjacentMap(lambda(F L)(cond((or(null? L)(null?(cdr L)))'())(else(cons(F (car L)(cadr L))(adjacentMap F (cdr L)))))))
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))'(555))⇒(0510)(mapIndexed list'(a b c))⇒((0 a)(1 b)(2 c))(mapIndexed +'())⇒()(mapIndexed (lambda(I X) I)'(x y z w))⇒(0123)(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.
(definemapFrom; i = position of (car L)(lambda(F i L)(cond((null? L)'())(else(cons(F i (car L))(mapFrom F (+ i 1)(cdr L)))))))(definemapIndexed(lambda(F L)(mapFrom F 0 L)))
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))'(12))⇒(1122)(flatMap (lambda(X)(if(even? X)(list X)'()))'(1234))⇒(24)(flatMap list'())⇒()(flatMap (lambda(L) L)'((a b)()(c)))⇒(a b c)(flatMap (lambda(N)(list N (* N 10)))'(3))⇒(330)
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.
(defineflatMap(lambda(F L)(cond((null? L)'())(else(append(F (car L))(flatMap F (cdr L)))))))
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 (listcdrcdrcar)'(a b c d))⇒ c
(pipeline '()42)⇒42(pipeline (list(lambda(L)(cons0 L)))'(1))⇒(01)(pipeline (listabs(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.
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 cdrnull?'(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.
(defineiterateUntil(lambda(F P X)(cond((P X) X)(else(iterateUntil F P (F X))))))
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'(123))⇒6(myFoldl cons'()'(123))⇒(321)(myFoldl (lambda(X Acc)(list X Acc))'()'(123))⇒(3(2(1())))(myFoldl *1'())⇒1(myFoldl (lambda(X Acc)(max X Acc))0'(492))⇒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.
(definemyFoldl(lambda(F Init L)(cond((null? L) Init)(else(myFoldl F (F (car L) Init)(cdr L)))))); Init is the accumulator
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.
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.
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.
(definedropKey; 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)))))))(defineuniqueBy(lambda(F L)(cond((null? L)'())(else(cons(car L)(uniqueBy F (dropKey F (F (car L))(cdr L))))))))
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?'(24136))⇒((24)(13)(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'(-112))⇒((-11)(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.
(definegroupAdjacentBy(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
(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.
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.
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.
(definemergeBy(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
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).
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?'(12345))⇒((#f3)(#t2))(countBy (lambda(x)(remainder x 3))'(1234))⇒((12)(21)(01))(countBy length'((a)(b c)(d)))⇒((12)(21))(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.
(definebump; 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))))))(definecountKeys(lambda(F L table)(cond((null? L) table)(else(countKeys F (cdr L)(bump table (F (car L))))))))(definecountBy(lambda(F L)(countKeys F L '())))
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 +'(12)'(1020)'(100200))⇒(111222)(zipWith3 list'(a b c)'(12)'(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.
(definezipWith3(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)))))))
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.
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)(defineinsertBy(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)))))(defineinsertionSortBy(lambda(LT L)(cond((null? L)'())(else(insertBy LT (car L)(insertionSortBy LT (cdr L)))))))
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 +'(123))⇒(345)(pairwise list'(a b c))⇒((a b)(a c)(b c))(pairwise *'(5))⇒()(pairwise -'(1012))⇒(98-1)
Show answer
Pair the first element with everything after it, then do the same for the rest. append joins the batches in order.
(definepairwise(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)))))))
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.
(definekeepFrom; 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))))))(definefilterIndex(lambda(P L)(keepFrom P 0 L)))
Write windows, which returns every run of N neighbouring elements of L, from left to right.
(windows 2'(1234))⇒((12)(23)(34))(windows 3'(a b c))⇒((a b c))(windows 3'(a b))⇒()(map(lambda(w)(apply+ w))(windows 2'(123)))⇒(35)
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.
(definefirstK(lambda(k L)(cond((= k 0)'())(else(cons(car L)(firstK (- k 1)(cdr L)))))))(definewindows(lambda(N L)(cond((<(length L) N)'()); not enough left for a window(else(cons(firstK N L)(windows N (cdr L)))))))
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(defineruns(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))))))(definemaxRunBy(lambda(P L)(runs P L 00)))
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)⇒(1491625)(unfold zero?(lambda(x) x)(lambda(x)(- x 1))3)⇒(321)(unfold null?carcddr'(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).
(defineunfold(lambda(STOP F NEXT SEED)(cond((STOP SEED)'())(else(cons(F SEED)(unfold STOP F NEXT (NEXT SEED)))))))
Carry the index along and output the index, not the element, whenever P holds.
(definepositionsFrom; 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))))))(definepositionsOf(lambda(P L)(positionsFrom P 0 L)))
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.
(definequicksortBy(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)))))))))
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.
(defineevalWith(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))))))))
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(12))))⇒((12)(12))(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.
(definecopies(lambda(n x)(cond((= n 0)'())(else(cons x (copies (- n 1) x))))))(definerleDecode(lambda(L)(cond((null? L)'())(else(append(copies (car(car L))(cadr(car L)))(rleDecode (cdr L)))))))
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.
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(definesubsets(lambda(L)(cond((null? L)(list'()))(else(let((rest (subsets (cdr L))))(append rest
(map(lambda(s)(cons(car L) s)) rest)))))))
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.
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 () ()).
(definebstInsert(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)))))))
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).
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 10'(12(1(1))))⇒(02(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.
(definedeepSubst(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)))))))
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).
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(definecountChange(lambda(Amount Coins)(cond((= Amount 0)1)((or(< Amount 0)(null? Coins))0)(else(+(countChange (- Amount (car Coins)) Coins)(countChange Amount (cdr Coins)))))))
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.
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 '(+12))⇒(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.
(definetoInfix(lambda(E)(cond((not(list? E)) E); a number or a variable(else(list(toInfix (cadr E))(car E)(toInfix (caddr E)))))))
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.
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.
(definepathSum(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)))))))
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.
Insert the numbers one at a time, left to right, carrying the tree built so far as an accumulator.
(definebstInsert(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)))))))(defineinsertAll; tree = the tree built so far(lambda(L tree)(cond((null? L) tree)(else(insertAll (cdr L)(bstInsert (car L) tree))))))(definelistToBST(lambda(L)(insertAll L '())))
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.
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(definecanSum(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)))))))
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.
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(definecountSubsetsSum(lambda(N L)(cond((null? L)(if(= N 0)10))(else(+(countSubsetsSum (- N (car L))(cdr L))(countSubsetsSum N (cdr L)))))))
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 '(12)'(a))⇒((12 a)(1 a 2)(a 12))(interleavings '(12)'(a b))⇒((12 a b)(1 a 2 b)(1 a b 2)(a 12 b)(a 1 b 2)(a b 12))
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(defineinterleavings(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))))))))
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.
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.
(definemaxSubsetSum(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
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.
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.
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.
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.
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).
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.
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)(defineparts(lambda(n k)(cond((= n 0)1)((or(< n 0)(= k 0))0)(else(+(parts (- n k) k)(parts n (- k 1)))))))(definecountPartitions(lambda(N)(parts N N)))
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.
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.
(definetreeDepthOf(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)))))))))
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: ().
(defineremoveOne(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(definepermutations(lambda(L)(cond((null? L)(list'()))(else(applyappend(map(lambda(x)(map(lambda(p)(cons x p))(permutations (removeOne x L))))
L))))))
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.
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(definecombinations(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)))))))
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)⇒(+10)(derive '(* x x)'x)⇒(+(* x 1)(*1 x))(derive '(*2(+ x y))'x)⇒(+(*2(+10))(*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.
(definederive(lambda(E V)(cond((number? E)0)((symbol? E)(if(equal? E V)10))(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)))))))))
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 '(+23))⇒5(simplify '(*(+11) 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.
(definesimplify(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))))))))
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 *.
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(definerpn(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))))))))(defineevalRPN(lambda(L)(rpn L '())))
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.
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 '(123241)'(243121))⇒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.
(definelcsLength(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
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.
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(defineaddTo(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))))))(definegroupAll(lambda(F L table)(cond((null? L) table)(else(groupAll F (cdr L)(addTo table (F (car L))(car L)))))))(definegroupBy(lambda(F L)(groupAll F L '())))
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.
(definefirstN(lambda(n L)(cond((= n 0)'())(else(cons(car L)(firstN (- n 1)(cdr L)))))))(defineskipN(lambda(n L)(cond((= n 0) L)(else(skipN (- n 1)(cdr L))))))(definesortedToBST(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))))))))
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.
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).
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(definesafe?(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))))))(definetryCols; 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)))))(defineplace(lambda(N placed)(cond((=(length placed) N)1); every row has a queen(else(tryCols N 0 placed)))))(definenQueens(lambda(N)(place N '())))
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.
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.
(defineremoveAt; L without position j(lambda(j L)(cond((= j 0)(cdr L))(else(cons(car L)(removeAt (- j 1)(cdr L)))))))(defineminor; drop row 0 and column j(lambda(M j)(map(lambda(row)(removeAt j row))(cdr M))))(defineexpand; 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)))))))(definedeterminant(lambda(M)(cond((null?(cdr M))(car(car M))); 1x1(else(expand M (car M)01)))))
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(definebuild(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)))'()))))))(defineallBalanced(lambda(N)(build N N)))
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 '(11))⇒((11))(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.
(defineremoveOne(lambda(x L)(cond((null? L)'())((equal? x (car L))(cdr L))(else(cons(car L)(removeOne x (cdr L)))))))(definedistinct; 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(defineuniquePerms(lambda(L)(cond((null? L)(list'()))(else(applyappend(map(lambda(x)(map(lambda(p)(cons x p))(uniquePerms (removeOne x L))))(distinct L)))))))
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.
countSubsetsSum that builds the subsets instead of counting them: "use it" conses the number onto the solutions for the smaller target.
(definesubsetsSumTo(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
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.
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.
(defineitem; 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)(definetermLoop(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(defineexprLoop(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)))))))(defineevalInfix(lambda(E)(let((t (termLoop (item (car E))(cdr E))))(exprLoop (car t)(cadr t)))))
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.
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).
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")(definelis(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(definelisLength(lambda(L)(lis L #f)))
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.
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".
(defineknapsack(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
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.
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(definecoinCombos(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
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.
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.(definerowCells; 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))))))(definelandCells(lambda(grid r)(cond((null? grid)'())(else(append(rowCells (car grid) r 0)(landCells (cdr grid)(+ r 1)))))))(defineneighbours(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))))))(defineflood; 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)))))))(definecountFrom(lambda(cells)(cond((null? cells)0)(else(+1(countFrom (flood (list(car cells))(cdr cells))))))))(definecountIslands(lambda(GRID)(countFrom (landCells GRID 0))))
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.
(definetranspose(lambda(M)(cond((null?(car M))'())(else(cons(mapcar M)(transpose (mapcdr M)))))));; take the top row, then turn what's left anticlockwise so the;; next edge to read becomes the new top row(definespiralOrder(lambda(M)(cond((null? M)'())((null?(cdr M))(car M))(else(append(car M)(spiralOrder (reverse(transpose (cdr M)))))))))
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.
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.
(definebstMin(lambda(T)(if(null?(cadr T))(car T)(bstMin (cadr T)))))(definebstDelete(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))))))))
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.
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 '(123)'(123))⇒(123)(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.
(definelcsList(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))))))
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.
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)(definepartsUpTo(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(definepartitionsList(lambda(N)(partsUpTo N N)))
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).
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.
(definenonIncreasing; already the last arrangement?(lambda(L)(or(null? L)(null?(cdr L))(and(>=(car L)(cadr L))(nonIncreasing (cdr L))))))(definelastBigger; 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)))))))(definereplaceFirst(lambda(old new L)(cond((equal?(car L) old)(cons new (cdr L)))(else(cons(car L)(replaceFirst old new (cdr L)))))))(definenextP(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)))))))(definenextPermutation(lambda(L)(if(nonIncreasing L)(reverse L); wrap round to the first arrangement(nextP L))))
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 sumWithand 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.
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:
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 cdr2)'(a b c d))⇒(c d)((repeated sqrt0)81)⇒81((repeated list3)'x)⇒(((x)))(map(repeated (lambda(x)(+ x 1))5)'(010))⇒(515)((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.
(definerepeated(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 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?)'(-23467))⇒(46)((keepAll)'(a b c))⇒(a b c)((keepAll number?)'())⇒()((keepAll number?(lambda(x)(> x 10))odd?)'(1112 x 135))⇒(1113)(let((smallEvens (keepAll even?(lambda(x)(< x 5)))))(list(smallEvens '(123456))(smallEvens '(80))))⇒((24)(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(definepassesAll(lambda(preds x)(cond((null? preds)#t)(((car preds) x)(passesAll (cdr preds) x))(else#f))))(definekeepAll(lambda preds
(lambda(L)(filter(lambda(x)(passesAll preds x)) L))))
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.
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(definecollect(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)))))))(definecurryN(lambda(f n)(collect f n '())))
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.
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))⇒(2010#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 ...)(definefindValue(lambda(k L)(cond((null? L)#f)((equal? k (car L))(cadr L))(else(findValue k (cddr L)))))); skip a key AND its value(definelookupFn(lambda pairs
(lambda(k)(findValue k pairs))))
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 biggestf 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
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(definebestOf(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))))))(definebestBy(lambda(f)(lambda args
(bestOf f (car args)(cdr args)))))
This is the mock's chain, turned inside out. startWith takes a valuex 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)
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.
Two functions made by withCount keep separate counts. You need set! (see makeCounter in Scope & Closures).
(let((plus (withCount +)))(plus 12))⇒3(let((plus (withCount +)))(plus 12)(plus 456)(plus))⇒2((withCount +))⇒0(let*((s (withCount sqrt))(a (s 16))(b (s 81)))(list a b (s)))⇒(492)(let((m (withCount max)))(m 12)(m)(m))⇒1(let((a (withCount list))(b (withCount list)))(a 1)(a 2)(b 3)(list(a)(b)))⇒(21)
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.
(definewithCount(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)))))))
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+)123)⇒(6)((chainMany sqrtsqrt+)60025)⇒5((chainMany +)1234)⇒10((chainMany lengthlist))⇒0((chainMany carreverselist)'a 'b 'c)⇒ c
((chainMany (lambda(x)(* x 10))-)31)⇒20(map(chainMany list-)'(56))⇒((-5)(-6))(let((f (chainMany lengthappend)))(list(f '(12)'(3))(f '(a)'(b)'(c d))))⇒(34)
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.
(definerunChain(lambda(fns args)(cond((null?(cdr fns))(apply(car fns) args)); last function gets all args(else((car fns)(runChain (cdr fns) args))))))(definechainMany(lambda fns
(lambda args
(runChain fns args))))
The house
Every problem in this section starts with these definitions loaded.
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.
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.
(definekeepAtoms; 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)))))))(definecontents(lambda(R)(keepAtoms (cdr R)))); skip the room's name
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.
Skip the room's name. Each object counts 1 and each sub-room counts all of ITS objects, which is a recursive call.
(definecountIn; 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)))))))(definecountObjects(lambda(T)(countIn (cdr T)))); the name doesn't count
True if this room's name matches, or if any sub-room (searched recursively) has it. Objects are never rooms, so skip them.
(defineanyHas; 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(definehasRoom(lambda(R T)(or(equal?(car T) R)(anyHas R (cdr T)))))
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.
First FIND the room, stopping at the first match. Then take its objects. Stopping early is what stops Library's objects appearing four times.
(definekeepAtoms(lambda(L)(cond((null? L)'())((list?(car L))(keepAtoms (cdr L)))(else(cons(car L)(keepAtoms (cdr L)))))))(definefindRoom; the first room named R, or #f(lambda(R T)(cond((equal?(car T) R) T)(else(findIn R (cdr T))))))(definefindIn(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))))))(defineobjects(lambda(R T)(let((room (findRoom R T)))(if room (keepAtoms (cdr room))'()))))
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.
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.
(definekeepAtoms(lambda(L)(cond((null? L)'())((list?(car L))(keepAtoms (cdr L)))(else(cons(car L)(keepAtoms (cdr L)))))))(definesearchRooms; 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))))))(definewhereIs(lambda(X T)(cond((member X (keepAtoms (cdr T)))(car T)); directly in T(else(searchRooms X (cdr T))))))
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.
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.
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.
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.
(definepathIn; 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))))))(definepathTo(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
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.
(definedepthsOf; ((name depth) ...) depth-first(lambda(T d)(cons(list(car T) d)(depthsIn (cdr T)(+ d 1)))))(definedepthsIn(lambda(L d)(cond((null? L)'())((list?(car L))(append(depthsOf (car L) d)(depthsIn (cdr L) d)))(else(depthsIn (cdr L) d)))))(definedeepest; 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))))))(definedeepestRoom(lambda(T)(let((all (depthsOf T 0)))(car(deepest (car all)(cdr all))))))
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.
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.
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 12)))(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.
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.)
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) …)).
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).
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 carcdrcdr)'(123))⇒3((composeAll)5)⇒5((composeAll (lambda(x)(* x 2))(lambda(x)(+ x 1)))5)⇒12((composeAll length)'(a b))⇒2(map(composeAll carreverse)'((12)(345)))⇒(25)
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.
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 +'(123)'(102030))⇒(112233)(myMapN -'(56))⇒(-5-6)(myMapN list'(12)'(a b)'(x y))⇒((1 a x)(2 b y))(myMapN +'()'())⇒()(myMapN (lambda(a b c)(+ a (* b c)))'(12)'(34)'(56))⇒(1626)
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.
(definecars; first element of every list(lambda(LL)(cond((null? LL)'())(else(cons(car(car LL))(cars (cdr LL)))))))(definecdrs; every list minus its first element(lambda(LL)(cond((null? LL)'())(else(cons(cdr(car LL))(cdrs (cdr LL)))))))(definemyMapN(lambda(F . lists)(cond((null?(car lists))'())(else(cons(apply F (cars lists))(apply myMapN F (cdrs lists)))))))
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))sqrt25)⇒(7)(chain sqrtsqrt625)⇒5(chain listlistlistlist'hugs)⇒((((hugs))))(chain sqrtsqrtsqrtsqrtsqrt5)⇒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.
(definechain(lambda args
(cond((null?(cdr args))(car args)); only the value is left(else((car args)(apply chain (cdr args)))))))
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))list25)⇒(7)(chainLeft cdrcdrcar'(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(definerunLeft(lambda(fns x)(cond((null? fns) x)(else(runLeft (cdr fns)((car fns) x))))))(definechainLeft(lambda args
(let((r (reverse args))); value is now first, functions reversed(runLeft (reverse(cdr r))(car r)))))
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))sqrt25)⇒(2557(7))(chainTrace -4)⇒(4-4)(chainTrace carcdr'(123))⇒((123)(23)2)(chainTrace (lambda(x)(* x x))(lambda(x)(* x x))3)⇒(3981)
Show answer
Like chain, but output every intermediate value, starting with the original one.
;; fns are in the order they get applied(definetraceRun(lambda(fns x)(cond((null? fns)(list x))(else(cons x (traceRun (cdr fns)((car fns) x)))))))(definechainTrace(lambda args
(let((r (reverse args))); (value lastFn ... firstFn)(traceRun (cdr r)(car r)))))
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.
(definechainOrFalse(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))))))))
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 cdrcar)'(123))⇒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.
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 +12)34)⇒10((partial list'a)'b 'c)⇒(a b c)((partial -10)3)⇒7((partial max)492)⇒9(map(partial *3)'(123))⇒(369)
Show answer
Remember the first arguments. When the rest arrive, apply f to all of them joined with append.
(definepartial(lambda(f . first)(lambda rest
(apply f (append first rest)))))
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-735)⇒-7(argmax length'(a b)'(c d e)'(f g h))⇒(c d e)(argmax -419)⇒1(argmax (lambda(x)0)56)⇒5
Show answer
Best-so-far with a score function. Replace only on a strictly higher score, so ties keep the first.
(definebestOf; 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))))))(defineargmax(lambda(f x . rest)(bestOf f x rest)))
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.
Write longestArg, which takes one or more lists as separate arguments and returns the longest one (the first one on a tie).
(longestArg '(1)'(23)'(45))⇒(23)(longestArg '(a b c))⇒(a b c)(longestArg '()'(x)'())⇒(x)(longestArg '(12)'(3456)'(7))⇒(3456)
Show answer
Compare the first list with the longest of the rest. >= keeps the earlier one on a tie.
(definelongestArg(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
Find the maximum value, then find the position of its first occurrence.
(defineposOf; position of the first x in L(lambda(x L)(cond((equal? x (car L))0)(else(+1(posOf x (cdr L)))))))(definemaxPosition(lambda nums
(posOf (applymax nums) nums)))
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 '(12345))⇒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.
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.
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).
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).
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 212345)⇒((12)(34)(5))(groupArgs 3'a 'b 'c)⇒((a b c))(groupArgs 2)⇒()(groupArgs 178)⇒((7)(8))
Show answer
(n . vals) names the size. Then take the first n as a group, skip them, and repeat.
(definefirstN(lambda(n L)(cond((or(= n 0)(null? L))'())(else(cons(car L)(firstN (- n 1)(cdr L)))))))(defineskipN(lambda(n L)(cond((or(= n 0)(null? L)) L)(else(skipN (- n 1)(cdr L))))))(definegroups(lambda(n L)(cond((null? L)'())(else(cons(firstN n L)(groups n (skipN n L)))))))(definegroupArgs(lambda(n . vals)(groups n vals)))
(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 +'(12)'(3))⇒6(callWithBoth list'(a)'(b c))⇒(a b c)(callWithBoth max'()'(492))⇒9(callWithBoth -'(10)'(12))⇒7
Show answer
Join the two lists, then apply f so every element becomes a separate argument.
(definecallWithBoth(lambda(f L1 L2)(apply f (append L1 L2))))
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.
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.
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.
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.
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 '((123)(456)))⇒((14)(25)(36))(flipRows '((12)(34)))⇒((13)(24))(flipRows '((a b c)))⇒((a)(b)(c))(flipRows '((1)(2)(3)))⇒((123))
Show answer
(apply map list M) is (map list row1 row2 …), which collects each column into a row.
(defineflipRows(lambda(M)(applymaplist M))); = (map list row1 row2 ...)
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 +'(101010))⇒(101112)(mapWithIndex *'())⇒()(mapWithIndex (lambda(i x)(if(even? i) x 0))'(5678))⇒(5070)
Show answer
Build the list of positions (0 1 2 …), then map over the positions and the elements together.
(definecountUp; (i i+1 ... n-1)(lambda(i n)(cond((= i n)'())(else(cons i (countUp (+ i 1) n))))))(definemapWithIndex(lambda(f L)(map f (countUp 0(length L)) L)))
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.
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.
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 '(1234)'(246)'(42))⇒(24)(intersectAll '(a b c))⇒(a b c)(intersectAll '(12)'(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.
(defineinEvery; is x in every list of LL?(lambda(x LL)(cond((null? LL)#t)((member x (car LL))(inEvery x (cdr LL)))(else#f))))(defineintersectAll(lambda(first . others)(filter(lambda(x)(inEvery x others)) first)))
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 '(112))⇒(12)(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(defineuniq(lambda(L)(cond((null? L)'())(else(cons(car L)(uniq (filter(lambda(y)(not(equal? y (car L))))(cdr L))))))))(defineunionAll(lambda lists
(uniq (applyappend lists))))
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'(23)'((4))5)⇒(12345)(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.
(defineflat(lambda(L)(cond((null? L)'())((list?(car L))(append(flat (car L))(flat (cdr L))))(else(cons(car L)(flat (cdr L)))))))(defineflattenArgs(lambda args
(flat args))); the arguments are just one big list
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.
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.
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).
Best-so-far using the distance abs (- x element). Replace only when an element is strictly closer.
(defineclosest; 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))))))(defineclosestTo(lambda(x L)(closest x (car L)(cdr L))))
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|.
Pair each element with the one before it by mapping - over (cdr L) and L without its last element.
(defineallButLast(lambda(L)(reverse(cdr(reverse L)))))(definestepChanges(lambda(L)(cond((or(null? L)(null?(cdr L)))'())(else(map-(cdr L)(allButLast L)))))); next minus previous
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.
Compute each row's sum, then find the position of the first maximum.
(defineposOf; position of the first x in L(lambda(x L)(cond((equal? x (car L))0)(else(+1(posOf x (cdr L)))))))(definebestRow(lambda(M)(let((sums (map(lambda(row)(apply+ row)) M)))(posOf (applymax sums) sums))))
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)'(709285))⇒ bob
(topScorer '(solo)'(1))⇒ solo
(topScorer '(a b c)'(599))⇒ 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.
(definenameWith; first name whose score is s(lambda(s names scores)(cond((=(car scores) s)(car names))(else(nameWith s (cdr names)(cdr scores))))))(definetopScorer(lambda(names scores)(nameWith (applymax scores) names scores)))
Build the powers (0 1 2 …), then add up c × x^p with a two-list map.
(definecountUp; (i i+1 ... n-1)(lambda(i n)(cond((= i n)'())(else(cons i (countUp (+ i 1) n))))))(definepolyEval(lambda(coeffs x)(let((powers (countUp 0(length coeffs))))(apply+(map(lambda(c p)(* c (expt x p)))
coeffs powers)))))
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.(definepredictShadow'(6151510))
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.(definepredictLexical'(115100))
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 carcdr)'(123))⇒2((compose2 (lambda(x)(* x x))(lambda(x)(+ x 1)))4)⇒25((compose2 lengthcdr)'(a b c))⇒2(map(compose2 carreverse)'((12)(345)))⇒(25)
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).
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.
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.
Don't run this code. Work it out by hand, call by call.
(definemakeCounter2(let((total 0))(lambda()(let((mine 0))(lambda()(set! total (+ total 1))(set! mine (+ mine 1))(list mine total))))))(definea(makeCounter2))(defineb(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)(definepredictShared'(24))
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.
(definemakeStack(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))))))))
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))⇒(252)(let*((m1 (memoize (lambda(x)(+ x 1))))(m2 (memoize (lambda(x)(* x 10)))))(m1 3)(list(m1 3)(m2 3)))⇒(430)
Show answer
Keep a private association list of (input answer). Check it with assoc before calling F, and store each new answer.
(definememoize(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))))))))
Apply the Collatz step and cons each number on. The base case 1 gives (1).
(definenextHail(lambda(n)(cond((even? n)(quotient n 2))(else(+(*3 n)1)))))(definehailstone(lambda(n)(cond((= n 1)'(1))(else(cons n (hailstone (nextHail n)))))))
The same recursion as hailstone, but count 1 per step instead of building the list.
(definenextHail(lambda(n)(cond((even? n)(quotient n 2))(else(+(*3 n)1)))))(definehailLength(lambda(n)(cond((= n 1)1)(else(+1(hailLength (nextHail n)))))))
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.
Best-so-far over n from lo to hi. Replace only on a strictly longer sequence, so the smallest n wins ties.
(definenextHail(lambda(n)(cond((even? n)(quotient n 2))(else(+(*3 n)1)))))(definehailLength(lambda(n)(cond((= n 1)1)(else(+1(hailLength (nextHail n)))))));; best = best n so far; check n, n+1, ..., hi(definebestFrom(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)))))(definelongestHail(lambda(lo hi)(bestFrom lo (+ lo 1) hi)))
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).
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)(definehanoi(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
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.
A countdown answer may use each number in Lat 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.
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(definenumbersIn(lambda(E)(cond((number? E)(list E))(else(append(numbersIn (cadr E))(numbersIn (caddr E)))))))(defineremoveOne; 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)))))))(defineallAvailable; 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))))(defineusesOnly(lambda(E L)(allAvailable (numbersIn E) L)))
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)).
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.(defineremoveOne(lambda(x L)(cond((null? L)'())((equal? x (car L))(cdr L))(else(cons(car L)(removeOne x (cdr L)))))))(definefindHit; 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))))))(definepickTwo; 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))))))))(definecombine; + 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))))))(definefirstFound; 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))))))))(definesearch(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))))))(definecountdownPM(lambda(T L)(let((answer (search T (map(lambda(n)(list n n)) L))))(if answer answer '()))))
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.
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)).(defineremoveOne(lambda(x L)(cond((null? L)'())((equal? x (car L))(cdr L))(else(cons(car L)(removeOne x (cdr L)))))))(definefindHit(lambda(T pool)(cond((null? pool)#f)((=(car(car pool)) T)(cadr(car pool)))(else(findHit T (cdr pool))))))(definepickTwo(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))))))))(definecombine(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))))))(definefirstFound(lambda(f L)(cond((null? L)#f)(else(let((r (f (car L))))(if r r (firstFound f (cdr L))))))))(definesearch(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))))))(definecountdown(lambda(T L)(let((answer (search T (map(lambda(n)(list n n)) L))))(if answer answer '()))))