What are the inputs, outputs, and side effects of
collatz
?
(define (collatz-next n)
(if (even? n)
(/ n 2)
(+ 1 (* 3 n))))
(define (collatz n)
(displayln n)
(cond
((= n 1) 1)
(else (+ 1 (collatz-next n)))))
collatz-next
quote
atom
(check if atom or null)
eq
(equality of atoms)
car
cdr
cons
cond
Function “remembers” out of scope variables
(define (makefilter op x)
(lambda (n) (op x n)))
(let ((my-filter (makefilter < 8)))
... (my-filter 6) ...)
Let’s simplify our quicksort code
(define (qsort lst)
(cond
((null? lst) '())
(else
(let* ((pivot (car lst))
(less-than? (lambda (x) (<= x pivot)))
(greater-than? (lambda (x) (> x pivot))))
(append
(qsort (filter less-than? (cdr lst)))
(list pivot)
(qsort (filter greater-than? (cdr lst))))))))
(define (qsort lst)
(cond
((null? lst) '())
(else
(let ((pivot (car lst)))
(append
(qsort (filter (makefilter <= pivot) (cdr lst)))
(list pivot)
(qsort (filter (makefilter > pivot) (cdr lst))))))))
How can we implement this?
(for i '(1 2 3 4)
(* i 2))
=> '(2 4 6 8)
Not with a function…
We can achieve the same result with
(map (lambda (i) (* i 2)) '(1 2 3 4))
But I liked the
for
loop syntax
Can we just expand the
for
loop into that?
The interpreter replaces your macros with another expression defined by a syntax rule
(define-syntax-rule (for var lst body)
(map (lambda (var) body) lst))
(define-syntax-rule (swap x y)
(let ([tmp x])
(set! x y)
(set! y tmp)))
(swap first second)
Because