marick / fp-oo

Code samples and exercise solutions for /Functional Programming for the Object-Oriented Programmer/
143 stars 49 forks source link

Solution for exercise 1-3 seems incorrect #51

Closed dh3014 closed 8 years ago

dh3014 commented 8 years ago

Hi, I just bought the book and finished reading ch1. After completing the exercises, I refer to the solution and find an answer is incorrect (seems typo). I guess it's no harm to correct it.

marick commented 8 years ago

Sorry for the delay. I think the given solution is correct.

The problem is to allow (add-squares 1 2 5) to return 30. To do that, you need a way to "gather" all the arguments into a single sequence that you can work with. & is the way to do that. With the book's definition, you get this:

user=> (def add-squares
     (fn [& numbers]
       (apply + (map * numbers numbers))))

user=> (add-squares 1 2 5)
30

Your solution requires add-squares to take a single argument, which leads to this:

user=> (def add-squares
     (fn [numbers]
       (apply + (map * numbers numbers))))
user=> (add-squares 1 2 5)
ArityException Wrong number of args (3) passed to: user$add-squares  clojure.lang.AFn.throwArity (AFn.java:437)

Your solution does work if the caller has to pass in a list of values:

user=> (add-squares [1 2 5])
30
dh3014 commented 8 years ago

Yes, I misunderstood the problem statement. Shame.