The ant simulation

17 views
Skip to first unread message

rob....@gmail.com

unread,
Aug 30, 2008, 10:52:22 AM8/30/08
to Clojure
In the ant simulation the world function looks like this

(def world
(apply vector
(map (fn [_]
(apply vector (map (fn [_] (ref (struct cell 0 0)))
(range dim))))
(range dim))))

I'm not sure why the calls to '(apply vector' are required. I have two
theories:

* It is to work round the lazy nature of map and force the creation of
all of the refs. If this is the case, can anyone enlighten me as to
why this might be necessary?
* It is a performance optimisation to make lookups of faster later.

A third theory is that neither of the above theories is correct.

Can anyone provide me with some insight?

Thanks,


Rob Lally.

Parth Malwankar

unread,
Aug 30, 2008, 11:01:19 AM8/30/08
to Clojure
vector takes individual elements as arguments and map
returns a list. If we simply (vector (map ..)) the entire
list returned by map is seen as a single element. Hence
'apply'.

user=> (vector 1 2 3)
[1 2 3]
user=> (map inc [1 2 3])
(2 3 4)
user=> (vector (map inc [1 2 3]))
[(2 3 4)]
user=> (apply vector (map inc [1 2 3]))
[2 3 4]
user=>

Parth

>
> Thanks,
>
> Rob Lally.

Rich Hickey

unread,
Aug 30, 2008, 11:09:41 AM8/30/08
to Clojure


On Aug 30, 10:52 am, "rob.la...@gmail.com" <rob.la...@gmail.com>
wrote:
> In the ant simulation the world function looks like this
>
> (def world
> (apply vector
> (map (fn [_]
> (apply vector (map (fn [_] (ref (struct cell 0 0)))
> (range dim))))
> (range dim))))
>
> I'm not sure why the calls to '(apply vector' are required. I have two
> theories:
>
> * It is to work round the lazy nature of map and force the creation of
> all of the refs. If this is the case, can anyone enlighten me as to
> why this might be necessary?
> * It is a performance optimisation to make lookups of faster later.

Yes, we want to look up by index, and so use a vector.

Note that (apply vector s) is never needed now, use (vec s) instead.

Rich

Robert Lally

unread,
Aug 30, 2008, 11:18:15 AM8/30/08
to clo...@googlegroups.com

2008/8/30 Parth Malwankar <parth.m...@gmail.com>


vector takes individual elements as arguments and map
returns a list. If we simply (vector (map ..)) the entire
list returned by map is seen as a single element. Hence
'apply'.

user=> (vector 1 2 3)
[1 2 3]
user=> (map inc [1 2 3])
(2 3 4)
user=> (vector (map inc [1 2 3]))
[(2 3 4)]
user=> (apply vector (map inc [1 2 3]))
[2 3 4]
user=>

Parth

Thanks for taking the time to reply Parth, it was the point of the vector call rather than the apply that was confusing me.

R.

Robert Lally

unread,
Aug 30, 2008, 11:18:41 AM8/30/08
to clo...@googlegroups.com
Thanks Rich.

2008/8/30 Rich Hickey <richh...@gmail.com>
Reply all
Reply to author
Forward
0 new messages