Skip to content

Instantly share code, notes, and snippets.

@chomy
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save chomy/90607eb536a46ff54da2 to your computer and use it in GitHub Desktop.

Select an option

Save chomy/90607eb536a46ff54da2 to your computer and use it in GitHub Desktop.
SICP Chapter 3.1
;; 3.1
(define (make-accumulator sum)
(lambda (n) (set! sum (+ sum n))))
;; 3.2
(define (make-monitored f)
(let ((count 0))
(lambda (param)
(cond ((eq? 'how-many-calls? param) count)
((eq? 'reset param) (set! count 0))
(else (set! count (+ 1 count))
(f param))))))
;; 3.3
(define (make-account balance passwd)
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount)))
"Insufficient founds"))
(define (deposit amount)
(set! balance (+ balance amount)))
(lambda (pass m)
(if (eq? pass passwd)
(cond ((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit))
"Incorrect Password")))
;; 3,4
(define (call-the-cops) (print "Cop! Here!!"))
(define (make-account2 balance passwd)
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount)))
"Insufficient founds"))
(define (deposit amount)
(set! balance (+ balance amount)))
(let ((count 0))
(lambda (pass m)
(if (eq? pass passwd)
(cond ((eq? m 'withdraw) (set! count 0) withdraw)
((eq? m 'deposit) (set! count 0) deposit))
(begin (set! count (+ count 1))
(if (= count 7) (lambda (m) (call-the-cops))
(lambda (m) "Incorrect password")))))))
;; 3.5
(use data.random)
(use gauche.generator)
(define (random-in-range lo hi)
(+ (* (car (generator->list (reals-between$ 0 1) 1)) (- hi lo)) lo))
(define is-in-circle
(lambda ()
(<= (+ (square (- (random-in-range 2 8) 5))
(square (- (random-in-range 4 10) 7)))
(square 3))))
(define (monte-carlo trial expr)
(define (iter n success)
(cond ((>= n trial) (/ success trial))
((expr) (iter (+ n 1) (+ success 1)))
(else (iter (+ n 1) success))))
(iter 0 0))
;; 3.6
(define rand
(let ((x 4112))
(lambda (cmd)
(cond ((eq? 'reset cmd) (lambda (new-val) (set! x new-val)))
((eq? 'generate cmd) (set! x (mod (+ (* 134214 x) 421441) 1000))
(inexact (/ x 1000)))
(else (error "Invarid Command"))))))
;;3.7
;;3.8
(define f
(let ((b4 9999))
(lambda (p)
(cond ((= b4 9999) (begin (set! b4 p) 0))
((= b4 0) 0)
(else 1)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment