[racket] Rookie Question on Functional Languages

From: Stephen Bloch (sbloch at adelphi.edu)
Date: Thu Dec 9 14:02:41 EST 2010

On Dec 9, 2010, at 1:51 PM, Luke Jordan wrote:

> Here's a rookie question that stems from HtDP 29.3.2.
> The idea is to test an expression a number of times while timing it and compare to another version of the same function.  The expression finds a route in a vector (graph) from node 0 to node 4.  The way I would do this in C/Python is with a while loop, while the counter is not zero execute the expression (ignore return value), and wrap it in the timer.  In Racket I came up with:
> (time (for-each
>        (lambda (dest) (find-route 0 dest Graph))
>        (make-list 1000 4)))
> It seems unnecessarily tricky, but I couldn't think of a better way.  Am I missing a piece?  Does it only seem tricky because Racket is my first functional language.

One problem with this, which even a rookie :-) can see, is that the "time" applies not only to finding the routes but to generating the list, which may mess up your statistics.  So what you really want is more like
(let ((fours (make-list 1000 4)))
   (time (for-each (lambda (dest) (find-route 0 dest Graph))

But you're quite right, it's silly to create a list of 1000 fours just so you can apply for-each to them.  A somewhat cleaner way is
(for [counter (in-range 1 1000)]
       (find-route 0 4 Graph))

This is (roughly) equivalent to the C++/Java code
for (int counter = 1; counter <= 1000; ++counter) {

Stephen Bloch
sbloch at adelphi.edu

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20101209/be4959a6/attachment.html>

Posted on the users mailing list.