Kaz Kylheku
5/10/2016 8:55:00 PM
On 2016-05-10, a.daniel.eliason@gmail.com <a.daniel.eliason@gmail.com> wrote:
> I wanted to scan consecutive pairs off a list. I almost had it:
>
> (loop
> for (a b) on '(1 2 3 4 5 6)
> do (print `(,a ,b)))
>
> But of course not what I wanted. I hashed it out:
>
> (loop
> for scanner = '(1 2 3 4 5 6) then (cddr scanner)
> while scanner
> for a = (car scanner)
> for b = (cadr scanner)
> do (print `(,a ,b)))
>
> Perfect but what a mess. At least LOOP let me try it. Such a mess
> would never be the only way in LOOP. Certainly should be able to
> specify the stepping function. Yay! Much better:
>
> (loop
> for (a b) on '(1 2 3 4 5 6) by #'cddr
> do (print `(,a ,b)))
WJ taking a day off today.
$ ./txr
This is the TXR Lisp interactive listener of TXR 140.
Use the :quit command or type Ctrl-D on empty line to exit.
1> [[callf (op mapcar list) identity cddr] '(1 2 3 4 5 6)]
((1 3) (2 4) (3 5) (4 6))
2> (tuples 2 '(1 2 3 4 5 6))
((1 2) (3 4) (5 6))
Notes:
(callf main-fun f0 f1 f2 ...) returns a function which applies
its arguments to each of the functions f0, f1, f2, .... From each of
these applications it retains the return value. These return values
then constitute the arguments in a call to main-fun, whose
value is ultimately returned.
Thus [callf (op mapcar list) identity cddr] gives us a
function which will pass its argument(s) to identity
and to cddr, and then do (mapcar list arg0 arg1) with these
two arguments. All we have to do is call it.
tuples is largely self-explanatory.
Here is another way:
3> (collect-each* ((a '(1 2 3 4 5 6))
(b (cddr a)))
(list a b))
((1 3) (2 4) (3 5) (4 6))
The noteworthy thing here is the treatment of a within the
binding sub-xpression of the collect-each* construct. Note
that we invoke (cddr a). What? Your eyes are not deceiving
you and there is no mistake. At that point in the code, the
variable a which is in scope is a list, as if the previous
(a '(1 2 3 4 5 6)) were a let binding. But then in the
body of the construct, these variables denote the elements
of those lists, iterated in parallel.