$ txr -i
1> (defvarl brackets '("(" ")" "[" "]" "<" ">")))
brackets
2> [brackets (range 0 : 2)]
("(" "[" "<")
3> [brackets (range 1 : 2)]
(")" "]" ">")
range generates lazy list of integers with a step size (the colon symbol defaults the second upper bound argument so the list is infinite). A list of integers can be used in the brackets notation to select elements. Put the two together and you have spaced selection.Regarding defvarl, there is defvar too; defvarl means that the symbol is not marked special and so rebindings are lexical. Often, it is overkill for a global variable to support rebinding. We just pollute the symbol with the special marker and then have to namespace it or put earmuffs on it just in case, even though it is ever used that way.
(defun ab (l)
"I'm too lazy to reverse the result back."
(defun _ (l a b f)
(if (null l)
(if f (list a b) (list b a))
(_ (cdr l) b (cons (car l) a) (not f))))
(_ l nil nil t))
(ab '())
(ab '(1))
(ab '(1 2))
(ab '(1 2 3 4 5 6 7 8 9 10))
;; ((9 7 5 3 1) (10 8 6 4 2))
(ab '(1 2 3 4 5 6 7 8 9 10 11))
;; ((11 9 7 5 3 1) (10 8 6 4 2))
I don't know how cute or ugly a solution for variable step could be though. `ab` is a nice partitioning building block, less general than every-nth surely.ps: Straight from the land of wishful lisping
(defun abn (l n)
(defun ono (n)
"builds a cons oo cycle of size n"
'unicorn)
(defun noo (c)
"rotates a cons cycle by one"
'unicorn)
(defun cooons (c v)
"cons v to the head of c"
'unicorn)
(defun _ (l c)
(if (null l)
c
(_ (cdr l) (noo (cooons c (car l))))))
(_ l (ono n))) #lang racket
(define-syntax-rule (defun name (arg ...) . body)
(define (name arg ...) . body))
(define nil null)
(define t #t)
(defun ab (l)
;; "I'm too lazy to reverse the result back."
(defun _ (l a b f)
(if (null? l)
(if f (list a b) (list b a))
(_ (cdr l) b (cons (car l) a) (not f))))
(_ l nil nil t))
(ab '())
(ab '(1))
(ab '(1 2))
(ab '(1 2 3 4 5 6 7 8 9 10))
;; ((9 7 5 3 1) (10 8 6 4 2))
(ab '(1 2 3 4 5 6 7 8 9 10 11))
;; ((11 9 7 5 3 1) (10 8 6 4 2))
...and you don't need to worry about recursion limits thanks to mandatory TCO.I'd avoid recursive code like that as much as possible.
I'd write:
(defun ab (l)
(loop while l collect (pop l) into a
while l collect (pop l) into b
finally (return (list a b))))Your last example is nice. I had to read the CLHS loop to have a clue about linearity of multiple termination clauses though :)
ps: funny, while googling I even found some lisp checker with a rule about nested defuns (## define-lisp-pattern nested-defuns)
http://www.cs.northwestern.edu/academics/courses/325/program...
Bonus points for a more efficient version for lists.