Skip to content

Commit

Permalink
fix log
Browse files Browse the repository at this point in the history
  • Loading branch information
nmheim committed Mar 19, 2024
1 parent 519956f commit d76f2bd
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 42 deletions.
3 changes: 3 additions & 0 deletions lectures/lecture05.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ before the compilation by a macro is possible.
```scheme
(define-syntax-rule (macro-if c a b)
(my-if c (thunk a) (thunk b)))
(define (my-if c a b)
(if c (a) (b)))
```
The macro defines a syntax rule whose pattern is `(macro-if c a b)`. Racket
searches for a portion of AST being a list of length $4$ starting with a symbol
Expand Down
86 changes: 44 additions & 42 deletions lectures/lecture05.rkt
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))

0 comments on commit d76f2bd

Please sign in to comment.