;; The first three lines of this file were inserted by DrRacket. They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname flatten) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
;; A deepList is either:
;; * empty, or
;; * (cons s adl) where a is a symbol or a deepList and adl is a deepList
;; Examples
(define dl0 '(a))
(define dl1 '(()) )
(define dl2 '((a) ((b))))
(define dl3 '((a ((b c)) d (e)) ((f) ((g)))))
(define dl4 '())
;;
;; Template for deepList
#|
(define (f ... dl ... )
(cond [(empty? dl) ... ]
[(cons? d1)
(cond [(symbol? (first dl)) ... (first dl) ... (flatten (rest dl)) ...)]
[(cons? (first dl)) ... (flatten (first dl)) ... (flatten (rest dl))])]))
|#
;; flatten: deepList -> symbol-list
;; Purpose: (flatten dl) consumes a deepList dl and concatenates all of
;; the symbols embedded in dl into a symbol-list where the symbols appear
;; in the same order as when dl is printed as string.
;; input to form a list of elements
;; Examples:
(check-expect (flatten dl0) '(a))
(check-expect (flatten dl1) empty)
(check-expect (flatten dl2) '(a b))
(check-expect (flatten dl3) '(a b c d e f g))
(check-expect (flatten dl4) empty)
;; Template Instantiation for flatten:
#|
(define (flatten dl)
(cond [(empty? dl) ... ]
[(cons? d1)
(cond [(empty? (first dl)) ... (flatten (rest dl))]
[(symbol? (first dl)) ... (first dl) ... (flatten (rest dl)))]
[(cons? (first dl)) ... (flatten (first dl)) ... (flatten (rest dl))])]))
|#
;; Code:
(define (flatten dl)
(cond [(empty? dl) empty]
[(cons? dl)
(cond [(empty? (first dl)) (flatten (rest dl))]
[(symbol? (first dl)) (cons (first dl) (flatten (rest dl)))]
[(cons? (first dl)) (append (flatten (first dl)) (flatten (rest dl)))])]))