Re: Scope Question



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.
.



Relevant Pages

  • Re: Simple search across lines?
    ... > [on ignoring newlines when searching] ... > If you ignred newlines as a character, the "you\ndid" sequence above ...
    (comp.editors)
  • Re: CurrentElement->next = CurrentElement->next->next (UNDEFINED?)
    ... > searching through the list (starting form the HEAD) then finding the ... you are not accessing the same object twice. ... question about sequence points etc. ...
    (comp.lang.c)
  • Sboot to PB Protocol
    ... Hi all - for those who have been searching for the protocol between PB and ... the target system for downloads here it is: ... Sequence is: ... Host sends: ...
    (microsoft.public.windowsce.platbuilder)
  • Timeout with full text index
    ... I am new to FTIs and I'm having a problem searching a text field in my ... regularly when searching by sequence. ...
    (microsoft.public.sqlserver.programming)