Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SICP 2.5
#lang racket
; 与えられた範囲の点での数値の積を返す
(define (product term a next b)
(define (iter x result)
(cond ((< b x) result)
(else (iter (next x) (* result (term x))))))
(iter a 1))
; test
(= 24 (product (lambda (x) x) 1 (lambda (x) (+ x 1)) 4))
; 階乗
(define (factorial n)
(product (lambda (x) x) 1 (lambda (x) (+ x 1)) 5))
; test
(= 120 (factorial 5))
(define (inc x) (+ x 1))
; 指数
(define (power term a next b)
(define (iter counter result)
(if (< b counter) result
(iter (next counter) (* result (term a)))))
(iter 1 1))
; test
(= 16 (power identity 2 inc 4))
; cons
(define (cons a b)
(* (power identity 2 inc a)
(power identity 3 inc b)))
; test
(= 6 (cons 1 1))
(= 36 (cons 2 2))
(= 12 (cons 2 1))
; 偶数?
(eq? #t (even? 2))
; 奇数?
(eq? #f (odd? 2))
(eq? #t (odd? 3))
; car
(define (car x)
(define (iter a count)
(if (even? a) (iter (/ a 2) (inc count))
count))
(iter x 0))
; test
(= 0 (car 3))
(= 1 (car 6))
(= 2 (car 36))
(= 2 (car 12))
; cdr
(define (cdr x)
(define (iter a count)
(if (div? a 3) (iter (/ a 3) (inc count))
count))
(iter x 0))
; 3の倍数も 2をかけると偶数だった
; car もこれで書き換えれば良いよ
(define (div? a b)
(= 0 (remainder a b)))
; test
(= 0 (cdr 2))
(= 1 (cdr 6))
(= 2 (cdr 36))
(= 2 (cdr 18))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.