Flipping Lists
Posted: Sun Feb 11, 2007 10:29 pm
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:
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:
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?
Code: Select all
(define (nrest lst)
(reverse (rest (reverse lst))))
(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)
)))))
(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?