atieu@skat.usc.edu (Anthony Tieu) (02/14/90)
I am a beginner at programming in LISP. Forgive me if this is too simple. I want to write a function that concatenate the 1st and 2nd word of a list in reverse order to the list itself. Example (cat '(a b c d e f g)) returns (B A A B C D E F G) This can be done by (cons (second l) (cons (first l) l)). The problem I have been facing is that I need to be able to do it with nested lists. Example (cat '(a b c d (f g h) i j (k l m) p)) should return (B A A B C D (G F F G H) I J (L K K L M) P) Can this be done recursively? Help! Anthony
D89.JOHNNY-BILLQUIST@AIDA.CSD.UU.SE (Johnny Billquist) (02/20/90)
In article <22858@usc.edu> atieu@skat.usc.edu (Anthony Tieu) writes: >I want to write a function that concatenate the 1st and 2nd >word of a list in reverse order to the list itself. Example > (cat '(a b c d e f g)) returns > (B A A B C D E F G) >This can be done by (cons (second l) (cons (first l) l)). >The problem I have been facing is that I need to be able to do it >with nested lists. Example > (cat '(a b c d (f g h) i j (k l m) p)) should return > (B A A B C D (G F F G H) I J (L K K L M) P) >Can this be done recursively? > >Help! >Anthony Sure thing. Not much problems actually, here's one sulution (*not* tested...) (defun cat (x) (cons (second x) (cons (first x) (check x)))) (defun check (x) (cond ((null x) '()) ((atom (first x)) (cons (first x) (check (rest x)))) (t (cons (cat (first x)) (check (rest x)))))) The only restrictions on these function are that you should not pass lists, or sub-lists with less than two elements, since you'll get some NIL's in that case. Hope you get the general idea. ====================================================================== Everybody know that the DECstation is a pdp8, which is a RISC, but where did MIPS computers get into it? - Johnny Billquist ======================================================================