Flipping Lists

Started by Jeremy Dunn, February 11, 2007, 02:29:30 PM

Previous topic - Next topic

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:



(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:



(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

#1
By the way, instead of nrest, see http://www.alh.net/newlisp/phpbb/viewtopic.php?p=5541#5541">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

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



http://artfulcode.net\">Artful code