programming language part b 第一周作业
代码
#lang racket
(provide (all-defined-out)) ;; so we can put tests in a second file
;; put your code below
;1
(define (sequence low high stride)
(if (> low high)
'()
(cons low (sequence (+ stride low) high stride))))
;2
(define (string-append-map xs suffix)
(map (lambda (el) (string-append el suffix)) xs))
;3
(define (list-nth-mod xs n)
(let ([xl (length xs)])
(cond
[(< n 0) (error "list-nth-mod: negative number")]
[(= 0 xl) (error "list-nth-mod: empty list")]
[else (car (list-tail xs (remainder n xl)))])))
;4
(define (stream-for-n-steps s n)
(if (= n 0)
'()
(cons (car (s)) (stream-for-n-steps (cdr (s)) (- n 1)))))
;5
(define funny-number-stream
(letrec ([f (lambda (x) (cons
(if (= 0 (remainder x 5))
(- x)
x)
(lambda () (f (+ x 1)))))])
(lambda () (f 1))))
;6
(define dan-then-dog
(letrec ([f (lambda (x) (if (string=? x "dan.jpg")
(cons "dan.jpg" (lambda () (f "dog.jpg")))
(cons "dog.jpg" (lambda () (f "dan.jpg")))))])
(lambda () (f "dan.jpg"))))
;7
(define (stream-add-zero s)
(letrec ([f (lambda (s) (cons (cons 0 (car (s))) (lambda () (f (cdr (s))))))])
(lambda () (f s))))
;8
(define (cycle-lists xs ys)
(letrec ([f (lambda (n) (cons (cons (list-nth-mod xs n) (list-nth-mod ys n))
(lambda () (f (+ n 1)))))])
(lambda () (f 0))))
;9
(define (vector-assoc a vec)
(letrec ([f (lambda (n) (cond
[(>= n (vector-length vec)) #f]
[(not (pair? (vector-ref vec n))) (f (+ n 1))]
[(equal? (car (vector-ref vec n)) a) (vector-ref vec n)]
[else (f (+ n 1))]))])
(f 0)))
;10
(define (cached-assoc xs n)
(letrec ([cache (make-vector n #f)]
[index 0]
[f (lambda (v) (let ([vres (vector-assoc v cache)])
(cond
[vres vres]
[(not vres) (let ([xres (assoc v xs)])
(cond
[xres (vector-set! cache index xres)
(set! index (remainder (+ 1 index) n))
xres]
[(not xres) #f]))])))])
f))
思考
Coursera提交有点问题,第一天GG了,第二题一模一样却过了
都是很有意思的几个流或者函数
这里有点不好的地方是,我又有个处理流的函数对流进行了重复计算
知识点回顾
1.和scheme不同的是,cons形成的list是不能更改的,要使用可以改的请用mcons
2.用thunk实现惰性求值,这是sicp讲过的
3.避免重复计算,也是我代码中不好的地方
4.定义流和使用流,,流就是一个thunk,求值后car中是值,cdr是一个thunk即另一个流
5.memoization技术来避免重复求值
6.宏的编写,syntax-rules中放的是其他的关键字
Yosoro