;; Data definition ;; ;; A NLON (short for Nested-List-of-Numbers) is one of ;; - empty ;; - (cons Number NLON) ;; - (cons NLON NLON) ;; NLON examples empty (cons 4 (cons 5 empty)) (cons (cons 1 (cons 2 (cons 3 empty))) (cons 4 (cons 5 empty))) #| Note that these can be written more concisely using the list function. Here are the same 3 examples written that way: empty (list 4 5) (list (list 1 2 3) 4 5) |# #| Template for a function consuming an NLON ;; f : NLON -> ??? (define (f a-nlon) (cond [(empty? a-nlon) ... ] [(number? (first a-nlon)) ... (first a-nlon) ... ... (f (rest a-nlon)) ... ] [(cons? (first a-nlon)) ... (f (first a-nlon)) ... ... (f (rest a-nlon)) ... ])) |# ;; add-all : NLON -> Number ;; adds up all numbers appearing in the given NLON (define (add-all a-nlon) (cond [(empty? a-nlon) 0] [(number? (first a-nlon)) (+ (first a-nlon) (add-all (rest a-nlon)))] [(cons? (first a-nlon)) (+ (add-all (first a-nlon)) (add-all (rest a-nlon)))])) ;; Examples/tests of add-all (= (add-all (list 4 5)) 9) (= (add-all (list (list 1 2 3) 4 5)) 15) ;; flatten : NLON -> LON ;; creates a single list containing all the numbers in the NLON (define (flatten a-nlon) (cond [(empty? a-nlon) empty] [(number? (first a-nlon)) (cons (first a-nlon) (flatten (rest a-nlon)))] [(cons? (first a-nlon)) (append (flatten (first a-nlon)) (flatten (rest a-nlon)))])) ;; Examples/tests of flatten (equal? (flatten (list 4 5)) (list 4 5)) (equal? (flatten (list (list 1 2 3) 4 5)) (list 1 2 3 4 5))