4034df6027cbecf3f4a19a711a248536

This is written in a dialect of lisp: scheme. The first 3 functions are helper functions, the main function is the last function. Basically it creates a list of varying depths by parsing a list of numbers. Each number represents the depth that the element in the new list should have. I'm hoping someone can come up with a more straight forward way to accomplish what the below code does.

(define (remove-subnodes n L)
  (cond ((null? L) `())
	((= n (car L)) L)
	(else (remove-subnodes n (cdr L)))))

(define (subnode-of? n1 n2)
  (< n1 n2))

(define (equal-nodes? n1 n2)
  (= n1 n2))

; Take a list of numbers and build a list 
; where subnodes are 1 less than thier parent
; nodes on the same level are equal. 
; 
; (build-list `(0 1 1 2 2 1 1 2 1 0)
; => (0 (1 1 (2 2) 1 1 (2) 1) 0)
;
; (build-list `(0 1 2 3 4 5 1 0))
; => (0 (1 (2 (3 (4 (5)))) 1) 0)
;
; (build-list `(1 2 1 2))
; => (1 (2) 1 (2))
;
(define (build-list L)
  (define (helper n L)
    (cond ((null? L) `())
	  ((subnode-of? n (car L))
           (cons (cons (car L) 
		       (helper (car L) (cdr L)))
		 (helper n (remove-subnoes n (cdr L)))))
	  ((equal-nodes? n (car L))
	   (cons (car L)
		 (helper (car L) (cdr L))))
	  (else `())))
  (cons (car L) (helper (car L) (cdr L))))

Refactorings

No refactoring yet !

4a403f635b1c0f61cf5de98f6a308f51

podhmo

January 6, 2011, January 06, 2011 03:31, permalink

No rating. Login to rate!

this is gauche(one of scheme interpreters). using match macro.

(define (build-list L)
  (define (remove-subnodes e xs)
    (or (member e xs) '()))
  (let loop ((n (car L)) (L L))
    (match L
      [() '()]
      [(n* . L*) 
       (cond ((= n n*) (cons n (loop n L*)))
             ((< n n*) (cons (cons n* (loop n* L*))
                             (loop n (remove-subnodes n L*))))
             (else '()))])))

Your refactoring





Format Copy from initial code

or Cancel