Re: Scope Question
- From: Paul Donnelly <paul-donnelly@xxxxxxxxxxxxx>
- Date: Tue, 29 Apr 2008 18:06:02 -0500
dstein64 <DStein64@xxxxxxxxx> writes:
Wow, I should really learn more about the scoping rules in Lisp. Any
suggested readings?
Anyhow, here's my current scope question:
Suppose I have a recursive function that is searching for elements in
a tree. How can I store a list such that it is not reset on each
recursive call to the search function?
In general, how can I initialize a variable within a function that
will not be reset on each recursive call to that function? I hope my
question is clear. If not, please let me know. Thanks.
If I understand the question, you want to pass it along as another
argument to the function, like so (the ACCUM argument).
(defun myfind (test sequence &optional (accum '()))
"Finds all items in SEQUENCE for which TEST is T."
(cond ((null sequence) accum)
((funcall test (car sequence))
(myfind test (cdr sequence) (cons (car sequence) accum)))
(t (myfind test (cdr sequence) accum))))
If you don't have/don't like optional arguments, something like
(defun myfind (test sequence)
"Finds all items in SEQUENCE for which TEST is T."
(myfind0 test sequence '()))
(defun myfind0 (test sequence accum)
"Helper function for MYFIND."
(cond ((null sequence) accum)
((funcall test (car sequence))
(myfind test (cdr sequence) (cons (car sequence) accum)))
(t (myfind test (cdr sequence) accum))))
Is the usual solution.
.
- References:
- Scope Question
- From: dstein64
- Scope Question
- Prev by Date: Re: Request for comments on LISP-newbie style
- Next by Date: Re: Request for comments on LISP-newbie style
- Previous by thread: Re: Scope Question
- Next by thread: Re: Scope Question
- Index(es):
Relevant Pages
|
|