Ex 2.33

7 views
Skip to first unread message

janu

unread,
Aug 21, 2011, 2:40:52 AM8/21/11
to p2pu...@googlegroups.com
Hello All,

This works for me ,

(defn my-map [p coll]
  (accumulate (fn [x y]  (if (nil? coll) nil (cons (p x) y))) nil coll))

But I see it as cheating because of my use of coll inside the anonymous function. I need your view here.

Emeka 

Andres Raba

unread,
Aug 21, 2011, 6:52:56 AM8/21/11
to p2pu...@googlegroups.com
Hello Emeka,

If you first define accumulate like this (adapted from the book):

(defn accumulate [op initial sequence]
  (if (empty? sequence)
      initial
      (op (first sequence)
          (accumulate op initial (rest sequence)))))

then your my-map could be simply this:

(defn my-map [p coll]
  (accumulate (fn [x y] (cons (p x) y)) nil coll))

Accumulate already separates the head and tail of collection, so you don't have to :-)

Andres

2011/8/21 janu <emeka...@gmail.com>

janu

unread,
Aug 22, 2011, 8:20:43 AM8/22/11
to p2pu...@googlegroups.com
Thanks
Reply all
Reply to author
Forward
0 new messages