;; 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-intermediate-reader.ss" "lang")((modname nested_lists) (read-case-sensitive #t) (teachpacks ((lib "testing.ss" "teachpack" "htdp") (lib "guess.ss" "teachpack" "htdp") (lib "master.ss" "teachpack" "htdp") (lib "draw.ss" "teachpack" "htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "testing.ss" "teachpack" "htdp") (lib "guess.ss" "teachpack" "htdp") (lib "master.ss" "teachpack" "htdp") (lib "draw.ss" "teachpack" "htdp"))))) ;; lists of lists (define lists (list 1 2 (list 4 5) (list 3 (list 6)))) ;; sum-nested-lists: list of lists of numbers -> integer ;; the function takes a list of lists of numbers of ;; arbitrary nesting and finds the sum of all its elements ;; (sum-nested-lists (list 1 2 (list 4 5) (list 3 (list 6))) ;; -> 21 ;; we assume that lol is a valid list of numbers (define (sum-nested-lists lol) (cond [(empty? lol) 0] [(number? (first lol)) (+ (first lol) (sum-nested-lists (rest lol)))] [else (+ (sum-nested-lists (first lol)) (sum-nested-lists (rest lol)))] ) ) (sum-nested-lists (list 1 2 (list 4 5) (list 3 (list 6)))) ;; expected value 21 (sum-nested-lists (list 1 2 (list 4 5) 3 6)) ;; expected value 21 (sum-nested-lists empty) ;; expected value 0 ;; contains?: number, list of lists of numbers -> boolean ;; the function takes a number and a list of lists of numbers ;; of arbitrary nesting and returns true if the given number ;; appears in the list and false otherwise (define (contains? lol num) (cond [(empty? lol) false] [(and (number? (first lol)) (= (first lol) num)) true] ;; a number not equal to num: [(number? (first lol)) (contains? (rest lol) num)] [else (or (contains? (first lol) num) (contains? (rest lol) num))] ) ) (contains? (list 2 (list 4 5) (list 7 8)) 3) ;; expected false (contains? (list 2 (list 4 5) (list 7 3)) 3) ;; expected true (contains? (list 2 (list 3 5) (list 7 3)) 3) ;; expected true (contains? (list 2 (list 2 (list 2 (list 3)))) 3) ;; expected true (contains? (list 2 (list 2 (list 2 (list 4)))) 3) ;; expected false