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