![]() |
Jupyter at Bryn Mawr College |
|
|
Public notebooks: /services/public/dblank / CS245 Programming Languages / 2016-Fall / Notebooks |
(define snoc
(lambda (item lst)
(cond
((null? lst) (cons item '()))
(else (cons (car lst)
(snoc item (cdr lst)))))))
(snoc 1 '()) ;; -> (1)
(snoc 'a '(c b)) ;; -> (c b a)
(snoc '4 '(1 2 3)) ;; -> (1 2 3 4)
(define rac
(lambda (lst)
(cond
((null? lst) (error 'rac "can't take the rac of an empty list"))
((null? (cdr lst)) (car lst))
(else (rac (cdr lst))))))
(rac '(1 2 3 4)) ;; -> 4
(rac '(a)) ;; -> a
(rac '())
Scheme (like Python) can take functions as arguments, and return them. This is called "functions as first-class objects."
(define add1
(lambda (number)
(+ 1 number)))
(map add1 '(1 2 3))
(define my-map
(lambda (f lst)
(cond
((null? lst) '())
(else (cons (f (car lst))
(my-map f (cdr lst)))))))
(my-map add1 '(1 2 3))
(map + '(1 2 3) '(3 4 5) '(100 100 100))
(define compose
(lambda (f g)
(lambda (lst)
(f (g lst)))))
(define my-cadr (compose car cdr)) ;; my-cadr is a <procedure>
(my-cadr '(1 2 3)) ;; -> 2
(map my-cadr '((1 2 3) (4 5 6) (7 8 9)))
Lab03 will begin the process of implementing Scheme in Python.
(import "math")
(math.pow 2 3)
(define expt math.pow)
(expt 3 5)