Fork me on GitHub

hahaha I should postpone solving this... I have read all my notes on the book so far at least four times just tonight, tried everything for hours here (for, map, reduce, consing, conjing, concating, everything) breaking stuff and it was nice because I'm getting more intimate with everything, but I still can't see how to make it work. There is probably some key detail that I'm missing, so I better move on to other chapters and come back later or I'll loose my motivation hehe. Two days is too much for a lost challenge dropped in the middle of an introductory chapter.


I can barely keep my eyes open now, so thank you everyone and have a nice day.


Yeah, this is a hard concept to get a grasp on, although once it “clicks” you’ll find it a lot easier to apply to future problems.


Highly recommend tackling it after a good night’s sleep, when you’re rested & fresh, etc.


Here’s an example that might be helpful for when you come back to this. Suppose we have a + function that only takes exactly 2 arguments, and we want to write an add-all function that can add up any number of arguments, including 1 and 0.

(defn add-all [& args]
  (case (count args)
    0 0
    1 (first args)
    2 (+ (first args) (second args))
    ; else
    (+ (first args) (apply add-all (next args)))))


This function actually has three base cases: if there are zero arguments, we just return zero, if there’s one argument we just return that argument, and if there’s two arguments, we return the first added to the second.


The last line demonstrates the key concept of recursion: There’s a list of things we want to process, so we peel off the first item of the list, and then recurse with the rest of the list. In other words, each time we recurse, our list is getting shorter, until finally it gets small enough to be handled by one of our base cases.


(add-all 1 2 3 4 5)
  (+ 1 (add-all 2 3 4 5))
  (+ 1 (+ 2 (add-all 3 4 5)))
  (+ 1 (+ 2 (+ 3 (add-all 4 5)))) ;; <== we've reached a base case
  (+ 1 (+ 2 (+ 3 (+ 4 5))))
  (+ 1 (+ 2 (+ 3 9)))
  (+ 1 (+ 2 12))
  (+ 1 14)


The trick is figuring out how to express the problem in terms of “I want to munge a list of x1, x2, x3...xN, and I can get that by munging x1 and (munge x2, x3...xN)