#lang racket (define (accumulate op initial sequence) (if (null? sequence) initial (op (car sequence) (accumulate op initial (cdr sequence))))) (define (square x) (* x x)) ;; 2.30 oooh, we getting cool now are we? (define (square-tree l) (cond ((null? l) l) ((list? (car l)) (cons (square-tree (car l)) (square-tree (cdr l)))) (#t (cons (square (car l)) (square-tree (cdr l)))))) (define (square-tree-map l) (map (λ (x) (if (list? x) (square-tree-map x) (square x))) l)) ;; 2.31 hohoohoho nice (define (tree-map f l) (map (λ (x) (if (list? x) (tree-map f x) (f x))) l)) (define (square-tree-final l) (tree-map square l)) ;; 2.32 hmm.. cool stuff. (define (subsets s) (if (null? s) (list '()) (let ((rest (subsets (cdr s)))) (append rest (map (λ (l) (cons (car s) l)) rest))))) ;; The reason this works, is because the set of subsets of a set s ;; can be defined as such: ;; - if s is the empty set, the result is a set containing the empty set ;; - otherwise, the result is a set containing: ;; 1. the subsets of s without the first element of s ;; 2. the subsets of s with the first element of s ;; 2 can be defined as the first element of s added to every ;; subset of s that does not contain the first element of s. ;; probably not a very rigorous or formal definition, but good ;; enough for now. ;; 2.33 (define (map p sequence) (accumulate (lambda (x y) ⟨??⟩) nil sequence)) (define (append seq1 seq2) (accumulate cons ⟨??⟩ ⟨??⟩)) (define (length sequence) (accumulate ⟨??⟩ 0 sequence))