2 ms·
Oh I wasn't arguing that CL loop was a far better solution than while loops (unless you process too long lists). I just became very very+ fond of academic recur
by agumonkey 11y ago
Oh I wasn't arguing that CL loop was a far better solution than while loops (unless you process too long lists). I just became very very+ fond of academic recursive style. Here's a singly-linear variant for fixed steps.
(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)))
- lispm 11y agoNested DEFUNs? Not in Lisp. In Common Lisp use LABELS for recursive local functions. 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))))
- agumonkey 11y agoOops, I forgot defun affected the global namespace. 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/programs/cs325/lisp-rules.lisp http://www.cs.northwestern.edu/academics/courses/325/program...
- klibertp 11y agoSome Schemes - most notably Racket, which I use the most - allow for nested defines. Your code actually is a valid Racket code after polishing the differences in naming and syntax a bit: #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.
- agumonkey 11y agoYeah, I spent too much time on scheme classes about recursive logic while using emacs lisp at the same time, hence the code above.