-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
47 additions
and
42 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,44 +1,46 @@ | ||
#lang racket | ||
|
||
;;; Lecture 6 - mutable data | ||
|
||
; set! | ||
(define x 1) | ||
x | ||
(set! x 2) | ||
x | ||
(set! x '(a b c)) | ||
x | ||
|
||
(define (make-counter) | ||
(define cnt 0) | ||
(lambda () | ||
(set! cnt (+ cnt 1)) | ||
cnt)) | ||
|
||
; pseudorandom number generator | ||
(define random | ||
(let ([a 69069] | ||
[b 1] | ||
[m (expt 2 32)] | ||
[seed 20210323]) | ||
(lambda args | ||
(if (null? args) | ||
(begin | ||
(set! seed | ||
(modulo (+ (* a seed) b) m)) | ||
(exact->inexact (/ seed m))) | ||
(set! seed (car args)))))) | ||
|
||
(random) | ||
(random 666) | ||
|
||
; vectors | ||
(define v (vector 1 2 3)) | ||
v | ||
(vector-ref v 2) | ||
(vector-set! v 2 "hi") | ||
v | ||
(make-vector 4 'a) | ||
(define v2 #('a 'b 'c)) ; v2 is immutable | ||
;(vector-set! v2 1 'd) | ||
;;; Lecture 5 - Streams and macros | ||
;;; Lazy evaluation | ||
|
||
; lazy evaluation of arguments via thunks | ||
(define (my-if c a b) | ||
(if c a b)) | ||
|
||
(define (my-lazy-if c a b) (if c (a) (b))) | ||
(my-lazy-if #t (thunk 0) (thunk (/ 1 0))) | ||
|
||
|
||
;;; Macros | ||
|
||
; lazy if | ||
(define-syntax-rule (macro-if c a b) | ||
(my-lazy-if c (thunk a) (thunk b))) | ||
|
||
(macro-if (< 0 1) 'then (/ 1 0)) | ||
|
||
; list comprehension | ||
(define-syntax list-comp | ||
(syntax-rules (: <- if) | ||
[(list-comp <expr> : <id> <- <lst>) | ||
(map (lambda (<id>) <expr>) <lst>)] | ||
|
||
[(list-comp <expr> : <id> <- <lst> if <cond>) | ||
(map (lambda (<id>) <expr>) | ||
(filter (lambda (<id>) <cond>) <lst>))])) | ||
|
||
(list-comp (+ x 2) : x <- (range 10) if (>= 3 x)) | ||
|
||
; log macro | ||
(define ((log-rt f fsymb) . xs) | ||
(let ([val (apply f xs)]) | ||
(printf "Function: ~a\n" fsymb) | ||
(printf "Arguments: ~a\n" xs) | ||
(printf "Result: ~a\n" val) | ||
val)) | ||
|
||
(define-syntax-rule (log f) (log-rt f 'f)) | ||
|
||
(map (log *) (range 5) (range 5)) | ||
(foldl (log cons) '() (range 3)) | ||
|