Skip to content

Instantly share code, notes, and snippets.

View yao2030's full-sized avatar

yao2030 yao2030

  • Shanghai, China
View GitHub Profile
(define (last-pair list1)
(if (= (length list1) 1)
(car list1)
(last-pair (cdr list1))))
(define (but-last list1)
(if (= (length list1) 1)
'()
(cons (car list1) (but-last (cdr list1)))))
(define (reverse x)
(if (null? x)
(define (same-parity a . b)
(let ((test (if (even? a)
even?
odd?)))
(cons a (parity a test b))))
(define (parity a test b)
(cond ((and (not (null? b))(test (car b))) (cons (car b) (parity a test (cdr b) )))
((null? b) '())
(else (parity a test (cdr b) ))))
(define (pascal row col)
(cond ((= col 0) 1)
((= col row) 1)
((< row col) 0)
(else (+ (pascal (- row 1) (- col 1))
(pascal (- row 1) col)))))
;; Exercise 1.39
;; sicp
(define (tan-cf x k)
(define (n i)
(if (= i 1)
x
(square x)))
(define (d i)
(- (* 2 i) 1))
(define (cont-frac n d k)
(define (d x)
(if (= (remainder x 3) 2)
(* 2 (+ (quotient x 3) 1))
1))
;; exercise 1.38, sicp
(define (cont-frac n d k)
(define (cont-help i result)
(if (= i 0)
result
(cont-help (- i 1) (/ (n i) (+ (d i) result)))))
(cont-help k 0.0))
(cont-frac (lambda (i) 1.0) (lambda (i) 1.0) 100)
;; A so-called k-term finite continued fraction
;; gives the value of the gold ratio
(define (cont-frac n d k)
(define (cont-help i result)
(if (= i k)
(/ 1.0 result)
(cont-help (+ i 1) (/ (n i) (+ (d i) result)))))
(cont-help 1 0.0))
(cont-frac (lambda (i) 1.0) (lambda (i) 1.0) 100)
;; A so-called k-term finite continued fraction
;; gives the value of the gold ratio
(define (filtered-accumulate combiner null-value term a next b predicate)
(if (> a b)
null-value
(combiner (if (predicate (term a))
(term a)
null-value)
(filtered-accumulate combiner null-value term (next a) next b predicate))))
(define (pi n)
(define (p-term x)
(if (even? x)
(/ x (- x 1))
(/ (- x 1) x)))
(define (p-next x)
(+ x 1))
(* 4.0 (product p-term 3 p-next n)))
(define (integral f a b n)
(define h (/ (- b a) n))
(define (i-next x) (+ x 1))
(define (i-term x)
(cond ((or (= x 0) (= x n)) (f (+ a (* x h))))
((even? x) (* 2 (f (+ a (* x h)))))
(else (* 4 (f (+ a (* x h)))))))
(* (/ h 3) (sum i-term 0 i-next n)))