Some 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.Yeah, I spent too much time on scheme classes about recursive logic while using emacs lisp at the same time, hence the code above.
Nested 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))))Oops, 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/program...
ps: Straight from the land of wishful lisping