Scheme (Racket) - Loop Libraries
Asked Answered
C

3

5

I have DrRacket Version 5.0.2, I've spent like 3 hours already looking for the right libraries to make while, dolist, and dotimes work. I know how to use them but I just can't find the right libraries. When I type dotimes for example it tells me unknown identifier.

PS: Do you have to use define-syntax in order to define these loops? I've tried (require srfi/42) but it does not work. I'm using #lang scheme.

Chung answered 13/12, 2011 at 8:35 Comment(2)
while, dolist and dotimes are Common Lisp forms. You certainly could write macros for them in Scheme, but maybe you really want a Common Lisp environment instead?Xavier
By the way, #lang scheme is a backwards compatibility language and is deprecated so you probably want to use #lang racket. Also, I suggest reading the guide as well (it's pretty good for these sorts of questions).Roman
X
9

You could use Racket's built-in iteration forms instead:

Instead of (dolist (x some-list) body-forms ...), you can write (for ((x some-list)) body-forms ...)

Instead of (dotimes (i n) body-forms ...), you could use (for ((i (in-range 0 n))) body-forms ...) or even simply (for ((i n)) body-forms ...), as long as n is a non-negative integer.

You could write syntax-rules macros to transform the CL-style loops into Racket-style ones, but it's probably not worth it. Racket's for-forms are more flexible than dotimes or dolist by themselves, since you can easily use them to iterate over several sequences at once.

Xavier answered 13/12, 2011 at 11:11 Comment(2)
Note that the documentation link is to the latest version of Racket, which at the time of this comment is 5.2. You mentioned that you're using 5.0.2, so be aware of the version difference.Anomalism
I only just noticed that for integer n you can use (for ((i n)) ...) as an equivalent for (for ((i (in-range 0 n))) ...). Neat!Xavier
S
1

There is also now an implementation of the Common Lisp loop macro for Racket. Import it like this:

(require (planet jphelps/loop))
Slobber answered 4/1, 2016 at 8:24 Comment(0)
R
0

Number is actually a sequence.

> (sequence->list 5)
'(0 1 2 3 4)

(for ((i (in-range n))) body-forms ...) works too. in-range is faster.

Rime answered 18/3, 2015 at 9:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.