[Top][All Lists]

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

Re: I'd like to marry while and mapcar...

From: Pascal J. Bourguignon
Subject: Re: I'd like to marry while and mapcar...
Date: Fri, 06 Feb 2015 17:52:45 +0100
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/24.3 (gnu/linux)

Barry Margolin <address@hidden> writes:

> In article <address@hidden>,
>  Eli Zaretskii <address@hidden> wrote:
>> > From: Marcin Borkowski <address@hidden>
>> > Date: Fri, 06 Feb 2015 13:56:48 +0100
>> > 
>> > What I'd need is kind of a marriage of while and mapcar: I'd like to run
>> > some function until it returns nil and make a list of all results it
>> > gives back until then.
>> Can't you use 'throw' from within the function called by mapcar?
> That would allow you to terminate the loop, but how will it return the 
> list of the results? The function doesn't get a reference to the list of 
> results, so what value would you throw?

And worse: with mapcar, you'd have to duplicate the result list
building.  You can avoid it with mapc, but you need to return it both
when the list is exhausted and in the early exit, which is clearly not

    (defun map-while (pred-fun list)
      (catch 'result
        (let ((results '()))
          (mapc (lambda (x) 
                  (let ((result (funcall pred-fun x)))
                    (if result
                        (push result results)
                        (throw 'result (nreverse results))))) 
          (nreverse results))))

    (map-while 'oddp '(1 3 5 4 6 8))
    --> (t t t)

__Pascal Bourguignon__       
“The factory of the future will have only two employees, a man and a
dog. The man will be there to feed the dog. The dog will be there to
keep the man from touching the equipment.” -- Carl Bass CEO Autodesk

reply via email to

[Prev in Thread] Current Thread [Next in Thread]