;; The first three lines of this file were inserted by DrScheme. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-advanced-reader.ss" "lang")((modname 10a) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #t #t none #f ()))) ;; constants: (define OL "OL") (define UL "UL") (define Mt "Mt") (define OneItem "OneItem") (define ConsItem "Cons") (define StringItem "EString") ;; ----------------------------------------------------------------------------- ;; String [Listof String] -> String ;; create a new expression (check-expect (new ConsItem '("a" "b")) "new ConsItem(a, b)") (define (new class fields) (string-append "new " class "(" (separate-with-commas fields) ")")) ;; String -> String ;; create new StingItem (watch!) (check-expect (newStringItem "a") (new StringItem '("\"a\""))) (define (newStringItem x) (new StringItem (list (format "~s" x)))) ;; [Listof String] -> String ;; convert a Scheme list into an Item list (check-expect (list->list '("a" "b" "c")) (new ConsItem `("a" ,(new ConsItem `("b" ,(new ConsItem `("c" ,(new Mt '())))))))) #; (check-expect (list->list '("a" "b" "c")) (new ConsItem `("a" ,(new ConsItem `("b" ,(new OneItem '("c"))))))) (define (list->list ls) (foldr (lambda (i r) (new ConsItem (list i r))) (new Mt '()) ls) #; (foldr (lambda (i r) (new ConsItem (list i r))) (new OneItem (list (last ls))) (all-but-last ls))) ;; Nat String -> [Listof String] ;; make a list of n string items (check-expect (a-list 2 "a") (new ConsItem (list (newStringItem "a1000") (new ConsItem (list (newStringItem "a1001") (new Mt '())))))) (define (a-list n s) (list->list (build-list n (lambda (i) (newStringItem (string-append s (number->string (+ i 1000)))))))) ;; [Listof String] -> String ;; separate the items with commans, combine into one string (check-expect (separate-with-commas '("a" "b" "c")) "a, b, c") (define (separate-with-commas l) (if (empty? l) "" (foldr (lambda (f r) (string-append f ", " r)) (last l) (all-but-last l)))) ;; libraries (define (last l) (first (reverse l))) (define (all-but-last l) (reverse (rest (reverse l)))) ;; ----------------------------------------------------------------------------- (define (deep n) (cond [(zero? n) (new OL (list (a-list 3 "level0")))] [else (new UL `(,(new ConsItem `(,(newStringItem `(,(format "header ~a" n))) ,(new ConsItem `(,(deep (sub1 n)) ,(a-list n (format "level ~a" n))))))))])) (define (main n) (display (format "~a" (deep n)))) (main 6)