Flipping Lists

For the Compleat Fan
Locked
Jeremy Dunn
Posts: 95
Joined: Wed Oct 13, 2004 8:02 pm
Location: Bellingham WA

Flipping Lists

Post by Jeremy Dunn »

Take a simple operation like (rest '(a b c d e)) which returns (b c d e). Suppose we wish to get all elements other than the last. We could define the following function:

Code: Select all

(define (nrest lst)
   (reverse (rest (reverse lst))))
In LISP we are always looking for higher generalities and we notice the general form (reverse (func (reverse lst))) where func is any operation that we might perform on a list. But we might want to use a function that takes other arguments as well and really want the form

(reverse (func (reverse lst) arg1 arg2 ... argN))

We can define the following function FLIP to do this:

Code: Select all

(define-macro (flip)
  (if (= (length (args)) 2)
        (reverse ((eval (args 0))
                  (reverse (eval (args 1)))))
        (reverse (eval (append '((eval (args 0)))
                               '((reverse (eval (args 1))))
                               (slice (args) 2)
                       )))))
Now instead of writing an NREST function we could write our statement as

(flip rest '(a b c d e))

I have found several situations where this double reversal occurs and in most cases this function avoids the need to write special reversal functions. For instance, how about doing a reverse SLICE as in

(flip slice '(a b c d e f g h) 2 3) -> (d e f)

This will only work with functions that take a list as their first argument. Should this be something we should have in the standard toolkit or something like it?

rickyboy
Posts: 607
Joined: Fri Apr 08, 2005 7:13 pm
Location: Front Royal, Virginia

Post by rickyboy »

By the way, instead of nrest, see Sammo's definition of butlast. He uses chop which probably is much faster.

Otherwise, I think the flip abstraction is interesting, even though I've never needed it beyond butlast (yet!). But I will keep it in mind. Anyone else?

--Ricky
(λx. x x) (λx. x x)

Jeff
Posts: 604
Joined: Sat Apr 07, 2007 2:23 pm
Location: Ohio
Contact:

Post by Jeff »

In traditional lisp, when building long lists with cons, you often end up needing to flip the list after its construction.
Jeff
=====
Old programmers don't die. They just parse on...

Artful code

Locked