Skip to content

Instantly share code, notes, and snippets.

@cleac
Created May 30, 2017 06:42
Show Gist options
  • Save cleac/3d112070d755ce1f175817b4dd4b8899 to your computer and use it in GitHub Desktop.
Save cleac/3d112070d755ce1f175817b4dd4b8899 to your computer and use it in GitHub Desktop.
Python style range implementation in lisp
(defun range(s &optional end step_)
(let
(
(start (cond
(end s)
(T 0)))
(end (cond
(end end)
(T s)))
(step_ (cond
(step_ step_)
(T 1)))
(result (list nil))
)
(loop
(push start (cdr (last result)))
(setq start (+ start step_))
(when
(or
(and (> step_ 0) (>= start end))
(and (< step_ 0) (<= start end)))
(return (cdr result))
)
)
)
)
@lispm
Copy link

lispm commented May 30, 2017

Which one could write as

(defun range (s &optional end (step 1))
  (if (null end)
      (loop for i below s by step collect i)
    (loop for i from s below end by step collect i)))

or

(defun range (s &optional end (step 1))
  (loop for i from (if end s 0) below (if end end s) by step
        collect i))

or even

(defun range (s &optional (end s end-passed) (step 1))
  (loop for i from (if end-passed s 0) below end by step
        collect i))

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