I'd write it this way:
(apply + (mapcat #(range 1 %) (range 2 14)))

I think idiomatically I would have written it with (partial range 1)
instead of #(range 1 %), but I prefer compact forms.

Mibu


On Dec 24, 8:57 pm, MattyDub <mattydu...@gmail.com> wrote:
> I was presented with the question "How many gifts, total, are
> mentioned in the song 'The 12 Days of Christmas'?" I thought, "Aha!
> I'll use clojure to figure it out."  But I wanted to do it
> idiomatically, using some functional constructs (with which I'm not
> very familiar).  First, I needed to know how many presents were given
> on day n:
> (defn sum-up-to [n]
>   "returns the sum of the positive integers from 1 to n"
>   (apply + 0
>          (map #(+ 1 %) (range n))))
>
> (As an aside, yes, I know this is the same series from the apocryphal
> story about Gauss as a child, and that the result is n+1/(n/2), but
> using that would defeat the purpose of learning these functional
> constructs).
>    The "apply + 0" is a little wonky, though, yes?  I think that
> reduce would be better, right?  So I change the function:
> (defn sum-up-to [n]
>   "returns the sum of the positive integers from 1 to n"
>   (reduce + (map #(+ 1 %) (range n))))
>
>    Then we need to find the sum of each of those days, from 1 to 12;
> first, let's get that sequence (just to make sure I'm doing it right),
> then let's add it up:
> user> (map sum-up-to (range 1 13))
> (1 3 6 10 15 21 28 36 45 55 66 78)
> user> (reduce + (map sum-up-to (range 1 13)))
> 364
>
>    (Originally, I didn't know about the 2-argument version of range,
> so I was using map and an anonymous inline function to add 1 to each
> result from range, like:
> (map #(sum-up-to (inc %)) (range 12))
> Then I thought "This can't be right, there has to be a way to do this
> already", and looked at the docs for range.  It's nice when you find
> something you want already exists - thanks, Rich!)
>    Fun times - thanks, clojure!
> -Matt
> PS I'm sure there are versions of this that are shorter (1 line?) or
> perform better (e.g., by caching previous sums or something) - but
> I'll leave those as an exercise for somebody else. ;)
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To post to this group, send email to clojure@googlegroups.com
To unsubscribe from this group, send email to 
clojure+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to