;; 2010-09-25 ;; The following is a solution using R5RS Scheme lisp to solve a lisp processing problem. ;; By Sourav Mukherjee sourav.work gmail ;; The problem is described in detail here: http://xahlee.org/UnixResource_dir/writ/notations_mma.html ;;input -> ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q r) (5 s t)) ;;output -> ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t)) (define (make-pair a b) (cons a b)) (define (number pair) (car pair)) (define (second pair) (car (cdr pair))) (define (third pair) (car (cdr (cdr pair)))) ;;cons second and third elements of short-lst to lst (define (cons-second-and-third-to short-lst lst) (cons (second short-lst) (cons (third short-lst) lst))) (define (take-and-remove n lstlst) (cond ((null? lstlst) (make-pair '() '())) ((= (number (car lstlst)) n) (let ((rest (take-and-remove n (cdr lstlst)))) (make-pair (cons-second-and-third-to (car lstlst) (car rest)) (cdr rest)))) (else (let ((rest (take-and-remove n (cdr lstlst)))) (make-pair (car rest) (cons (car lstlst) (cdr rest))))))) ;; > (take-and-remove 1 '((1 a b) (1 c d) (2 e f) (1 g h) (4 i j))) ;; ((a b c d g h) (2 e f) (4 i j)) ;; > (take-and-remove 2 '((0 u v) (1 a b) (2 c d) (2 e f) (1 g h) (2 i j))) ;; ((c d e f i j) (0 u v) (1 a b) (1 g h)) ;; > (take-and-remove 5 '((0 u v) (1 a b) (2 c d) (2 e f) (1 g h) (2 i j))) ;; (() (0 u v) (1 a b) (2 c d) (2 e f) (1 g h) (2 i j)) ;; > (take-and-remove 5 '()) ;; (()) ;;THIS is the function we want (define (f lstlst) (cond ((null? lstlst) '()) (else (let ((answer-yet (take-and-remove (number (car lstlst)) (cdr lstlst)))) (cons (cons-second-and-third-to (car lstlst) (car answer-yet)) (f (cdr answer-yet))))))) ;; > (f '((1 a b) (1 c d) (2 e f) (1 g h) (4 i j))) ;; ((a b c d g h) (e f) (i j)) ;; > (f '((0 u v) (1 a b) (2 c d) (2 e f) (1 g h) (2 i j))) ;; ((u v) (a b g h) (c d e f i j)) ;; > (f '((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q r) (5 s t))) ;; ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))