braveandtrue

https://www.braveclojure.com/
felipebarros 2018-12-21T07:07:12.004500Z

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.

felipebarros 2018-12-21T07:11:06.005700Z

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

2018-12-21T14:44:17.006700Z

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.

2018-12-21T15:34:45.007300Z

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

2018-12-21T15:41:41.009Z

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)))))

2018-12-21T15:43:16.010200Z

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.

2018-12-21T15:45:15.011800Z

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.

2018-12-21T15:48:33.012100Z

(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)
  15

2018-12-21T15:53:23.014Z

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)