Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's range() analog in Common Lisp

How to create a list of consecutive numbers in Common Lisp?

In other words, what is the equivalent of Python's range function in Common Lisp?

In Python range(2, 10, 2) returns [2, 4, 6, 8], with first and last arguments being optional. I couldn't find the idiomatic way to create a sequence of numbers, though Emacs Lisp has number-sequence.

Range could be emulated using loop macro, but i want to know the accepted way to generate a sequence of numbers with start and end points and step.

Related: Analog of Python's range in Scheme

like image 315
Mirzhan Irkegulov Avatar asked Dec 18 '12 16:12

Mirzhan Irkegulov


2 Answers

There is no built-in way of generating a sequence of numbers, the canonical way of doing so is to do one of:

  • Use loop
  • Write a utility function that uses loop

An example implementation would be (this only accepts counting "from low" to "high"):

(defun range (max &key (min 0) (step 1))    (loop for n from min below max by step       collect n)) 

This allows you to specify an (optional) minimum value and an (optional) step value.

To generate odd numbers: (range 10 :min 1 :step 2)

like image 109
Vatine Avatar answered Oct 02 '22 18:10

Vatine


alexandria implements scheme's iota:

(ql:quickload :alexandria) (alexandria:iota 4 :start 2 :step 2) ;; (2 4 6 8) 
like image 38
Pavel Penev Avatar answered Oct 02 '22 20:10

Pavel Penev