[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: peasant revolt against DrScheme!



Shriram Krishnamurthi schrieb:
> Reini Urban wrote:
> > Even recursion is an advanced topic, and thanksfully nobody is
> > forced to write recursive in lisp/scheme.
> 
> Quick quiz: If you had to teach recursion, what is the first example
> you would use?  (You may give multiple examples, but they must all be
> ones you would cover in the first week of teaching it.)

FACTORIAL of course, as bad and easy example for the start.
I actually use it in the faq in the teaching. 
  http://xarch.tu-graz.ac.at/autocad/news/faq/autolisp.html#9
plus for memoization and self-modification then.
  http://xarch.tu-graz.ac.at/autocad/lisp/self-mod.lsp
FIBONACCI is not as good.

And as good counter example something more complicated, which looks terrible
iterative:
MAPATOM, map a function to every symbol in a tree, keeping the tree structure
intact.
(as destructuring-bind in cl)

  http://xarch.tu-graz.ac.at/autocad/stdlib/archive/3/msg00054.html
  against the recursive version in
http://xarch.tu-graz.ac.at/autocad/stdlib/STDLIST.LSP
  25 lines against 8.

it is more motivating to write a new one, instead of recreating a builtin, 
like REMOVE, LENGTH, REVERSE or such. the recursive versions of these are not
really 
persuasing. MEMBER and UNION are better.
of course MATCH in the third week then.

for tail-recursion I use HEAD (or FIRSTN) from Winston-Horn.
though the iterative version is also more convincing to newbies here.

;;; list of only the first n elements
;;; head - list till (including) the n-th element, base 0
(defun head (l n)
  (cond ((zerop n) nil)
	(t (cons (car l) (head (cdr l) (1- n))))))
;;; not tail-recursive, (cons) and (car l) stay on the stack

;;; trick to make it tail-recursive with the helper symbol x
(defun head (l n) (head-rec l nil n))
(defun head-rec (l x n)
  (cond ((zerop n) (reverse x))
	(t (head-rec (cdr l) (cons (car l) x) (1- n)))))

-- 
Reini Urban
http://xarch.tu-graz.ac.at/autocad/news/faq/autolisp.html