Wednesday, June 09, 2004

A Range Function

The range function in Python is quite useful for generating lists of numbers quickly. It is often used with 'for' as a basic iterative construct. The same effect can easily be achieved with Lisp and the Loop macro. Here is an example of how range works


Python 2.2.3 (#1, Nov 8 2003, 23:39:13)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> range(5)
[0, 1, 2, 3, 4]
>>> range(2,10)
[2, 3, 4, 5, 6, 7, 8, 9]
>>> range(2,10,2)
[2, 4, 6, 8]
>>> range(-10,-2)
[-10, -9, -8, -7, -6, -5, -4, -3]
>>> range(-10,-2,2)
[-10, -8, -6, -4]
>>> def square (x): return x * x
...
>>> square

>>> for x in range(5): print square(x)
...
0
1
4
9
16
>>>


Here is my Lisp function for the same using Lisp with Loop


(defun range (n &rest parms)
(case (length parms)
((0) (loop for x from 0 to n collect x))
((1) (loop for x from n to (first parms) collect x))
(t (let ((start n)
(stop (first parms))
(step (second parms)))
(loop for x = start then (+ x step) until (>= x stop)
collect x)))))


Its a little different because I have inclusive of the highest number. That is the easiest thing to modify. here is a test


[6]> (range 5)
(0 1 2 3 4 5)
[7]> (range 2 10)
(2 3 4 5 6 7 8 9 10)
[8]> (range 2 10 2)
(2 4 6 8)
[9]> (range -10 -2)
(-10 -9 -8 -7 -6 -5 -4 -3 -2)
[10]> (range -10 -2 2)
(-10 -8 -6 -4)
[11]> (defun square (x) (* x x))
SQUARE
[12]> (loop for x in (range 5) do (print (square x)))

0
1
4
9
16
25
NIL
[13]>


The Loop macro is much more powerful than the usage shown here but it can look ugly from a Lisp perspective.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home