Skip to content

Instantly share code, notes, and snippets.

@chomy
Created February 6, 2014 06:21
Show Gist options
  • Save chomy/8839184 to your computer and use it in GitHub Desktop.
Save chomy/8839184 to your computer and use it in GitHub Desktop.
function iota in common lisp
(defun iota (m &optional (n 1) (step 1))
(defun iter (m n lst)
(cond ((> n m) (reverse lst))
(t (iter m (+ n step) (cons n lst)))))
(iter m n nil))
@Harleqin
Copy link

Harleqin commented Jan 1, 2015

No. Don't use defun inside another defun. The inner defun will create or overwrite a global function, so as soon as you use the same "inner" function name elsewhere, the two will constantly trip over each other!

Use labels here (flet in other cases).

Also, don't assume tail call elimination for portable Common Lisp code. This will blow the stack on ABCL, for example, because ABCL cannot provide TCO due to the JVM's design.

Finally, always define standard ranges as inclusive-exclusive. See Dijkstra.

A better definition of iota is: (defun iota (end &optional (start 0) (step 1)) (loop :for n :from start :below end :by step :collect n)).

Finally, use the library of Alexandria (available from Quicklisp), which gives you a iota that also handles numeric contagion consistenty.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment