Created
August 17, 2018 11:32
-
-
Save apreiml/f62c257b2e90a49712d189d13dcfade3 to your computer and use it in GitHub Desktop.
Requires sicp plugin: # raco pkg install sicp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang sicp | |
(define (accumulate op initial sequence) | |
(if (null? sequence) | |
initial | |
(op (car sequence) (accumulate op initial (cdr sequence))))) | |
(accumulate + 0 (list 1 2 3)) | |
; Exercise 2.33 | |
(define (map p sequence) | |
(accumulate (lambda (x y) (cons (p x) y)) nil sequence)) | |
(define (append seq1 seq2) | |
(accumulate cons seq2 seq1)) | |
(define (length sequence) | |
(accumulate (lambda (x y) (+ x 1)) 0 sequence)) | |
; Exercise 2.34 | |
(define (horner-eval x coefficient-sequence) | |
(accumulate (lambda (this-coeff higher-terms) (+ this-coeff (* x higher-terms))) | |
0 | |
coefficient-sequence)) | |
; (horner-eval 2 (list 1 3 0 5 0 1)) | |
; Exercise 2.35 | |
(define (count-leaves t) | |
(accumulate + 0 (map (lambda (x) (if (list? x) (count-leaves x) 1)) t))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment