Helpful List Function
Posted: Wed Jun 13, 2007 2:38 am
One thing I always love about LISP is that it always gets you thinking in ever more general terms after you start out with something simple. Here is a good example of it. My starting point was a one-liner that I wrote that is pretty much self-explanatory:
(define (length? lst n)(= (length lst) n))
Can't get much simpler than that. I don't know how many times I wrote (= (length lst) n) before thinking of it. Just like the paper clip. But what about greater abstraction? What do we do with that length once we get it? I find that I either use it in a control structure to branch the program or I use it in a calculation. Let us just consider the control structure aspect of it. Here is the code first:
So what does iflength do? iflength gobbles up the previous function and acts as a control structure too. Let i be the length of the list, n the number we are comparing to the list, lst the list itself and X,Y,Z are code chunks to be executed depending on how a boolean test is performed. So it goes like this, if we write
(iflength lst n X Y Z) - if i<n then X is executed elseif i=n then Y is executed else Z is executed.
(iflength lst n X Y) - if i=n then X is executed else Y is
(iflength lst n X) - if i=n then X is executed else nothing happens
(iflength lst n) - behaves the same as the length? function
Very simple, very handy.
(define (length? lst n)(= (length lst) n))
Can't get much simpler than that. I don't know how many times I wrote (= (length lst) n) before thinking of it. Just like the paper clip. But what about greater abstraction? What do we do with that length once we get it? I find that I either use it in a control structure to branch the program or I use it in a calculation. Let us just consider the control structure aspect of it. Here is the code first:
Code: Select all
(define (iflength lst (n 0) X Y Z , i flg)
(setq i (length lst) flg (= i n))
(if Z (if (< i n) X flg Y Z)
Y (if flg X Y)
X (if flg X)
flg
))
(iflength lst n X Y Z) - if i<n then X is executed elseif i=n then Y is executed else Z is executed.
(iflength lst n X Y) - if i=n then X is executed else Y is
(iflength lst n X) - if i=n then X is executed else nothing happens
(iflength lst n) - behaves the same as the length? function
Very simple, very handy.