Created
November 25, 2014 18:40
-
-
Save qzdc00/c3f41943bec7ad398b2e to your computer and use it in GitHub Desktop.
hw4/WashingtonPLMOOC
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 racket | |
(provide (all-defined-out)) ;; so we can put tests in a second file | |
;; put your code below | |
(define sequence | |
(lambda (low high stride) | |
(if (> low high) | |
null | |
(cons low (sequence (+ low stride) high stride))))) | |
(define (string-append-map xs suffix) | |
(map (lambda (str) (string-append str suffix)) xs)) | |
(define (list-nth-mod xs n) | |
(cond [(< n 0) (error "list-nth-mod: negtive number")] | |
[(null? xs) (error "list-nth-mode: empty list")] | |
[#t (letrec ([l (length xs)] | |
[i (remainder n l)]) | |
(car (list-tail xs i)))])) | |
(define (stream-for-n-steps s n) | |
(define pair (s)) | |
(if (= n 0) | |
null | |
(cons (car pair) (stream-for-n-steps (cdr pair) (- n 1))))) | |
(define funny-number-stream | |
(letrec ([f (lambda (x) | |
(cons (if (= (remainder x 5) 0) (- 0 x) x) (lambda () (f (+ x 1)))))]) | |
(lambda () (f 1)))) | |
(define dan-then-dog | |
(letrec [(f (lambda (x) (cons x (lambda () (f (if (string=? x "dan.jpg") "dog.jpg" "dan.jpg"))))))] | |
(lambda () (f "dan.jpg")))) | |
; stream-add-zero is like "f" in dan-then-dog. Thunk here is lile thunk above. | |
(define (stream-add-zero s) | |
(letrec ([pair (s)] | |
[f (lambda () (stream-add-zero (cdr pair)))]) | |
(lambda () (cons (cons 0 (car pair)) (f))))) | |
(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)))) | |
(define (vector-assoc v vec) | |
(letrec ([len (vector-length vec)] | |
[f (lambda (index) | |
(if (equal? index len) #f (letrec ([cur (vector-ref vec index)]) | |
(cond [(pair? cur) (if (equal? (car cur) v) cur (f (+ index 1)))] | |
[#t (f (+ index 1))]))))]) | |
(f 0))) | |
(define (cached-assoc xs n) | |
(letrec ([cache (make-vector n #f)] | |
[index 0] | |
[f (lambda (v) | |
(letrec ([cached (vector-assoc v cache)] | |
[idx (remainder index n)]) | |
(if cached | |
(cdr cached) | |
(letrec ([new (assoc v xs)]) | |
(if new | |
(begin (vector-set! cache idx (cons v new)) | |
(set! idx (+ index 1)) | |
new) | |
#f)))))]) | |
f)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment