Using throw to return a value?
Posted: Sun Dec 20, 2009 6:31 pm
Hi. I suppose I should say I'm new to lisp first.
I found the following code in Maxima (src/commac.lisp) and was wondering why it was written this way...
I understand what it is doing (I think), but I don't understand why it was done with a throw (and a special case for eq?) rather than a naive
I thought maybe a performance hack? I tried using (time (appears-in ...)) with long and deeply nested lists, but there didn't seem to be much difference. Can anyone tell me why the code was written this way? (Also, is there a standard function for this sort of thing?)
Thanks alot.
P.S. Apologies for the awful indentation. How do I make <pre> tags?
I found the following code in Maxima (src/commac.lisp) and was wondering why it was written this way...
Code: Select all
(defun appears (tree var)
(cond ((equal tree var)
(throw 'appears t))
((atom tree) nil)
(t (appears (car tree) var)
(appears (cdr tree) var)))
nil)
(defun appears1 (tree var)
(cond ((eq tree var)
(throw 'appears t))
((atom tree) nil)
(t
(appears (car tree) var)
(appears (cdr tree) var)))
nil)
(defun appears-in (tree var)
"Yields t if var appears in tree"
(catch 'appears
(if (or (symbolp var) (fixnump var)) ; (fixnump var) is (typep var 'fixnum)
(appears1 tree var)
(appears tree var))))
Code: Select all
(defun appears-in (tree var)
(cond ((equal tree var) t)
((atom tree) nil)
(t (or (appears-in (car tree) var) (appears-in (cdr tree) var)))))
Thanks alot.
P.S. Apologies for the awful indentation. How do I make <pre> tags?