Skip to content

Instantly share code, notes, and snippets.

View chelseatroy's full-sized avatar

Chelsea Troy chelseatroy

View GitHub Profile
@chelseatroy
chelseatroy / scheme.py
Last active November 3, 2019 22:55
Interpreter 1: No Scope
# scheme.py
#
# Challenge: Can you implement a mini-scheme interpreter?
env = {
'+' : lambda x, y: x + y,
'-' : lambda x, y: x - y,
'*' : lambda x, y: x * y,
'/' : lambda x, y: x / y,
'!=' : lambda x, y: x != y,
'=' : lambda x, y: x == y,
@chelseatroy
chelseatroy / scheme.py
Created November 3, 2019 22:50
Interpreter Tests
assert seval(23, {}) == 23
assert seval("x", {"x": 23}) == 23
assert seval(("+", 1, 2), env) == 3
assert seval(("+", 1, ("*", 2, 3)), env) == 7
seval(("define", "x", 13), env) == 7
assert seval(("x"), env) == 13
assert seval(("if", ("<", 2, 3), 4, 5), env) == 4
assert seval(("if", (">", 2, 3), 4, 5), env) == 5
class WidthVisitor implements BoxVisitor {
int visitBob(BobBox box) {
return box.getWidth();
}
int visitAlice(AliceBox box) {
return Math.abs(box.getX2() - box.getX1());
}
}
@chelseatroy
chelseatroy / BobAndAlice.java
Last active November 3, 2019 14:21
Visitor Pattern
interface BoxVisitor {
int visitBob(BobBox box); ​
int visitAlice(AliceBox box);
}
...
abstract class Box {
abstract void accept(BoxVisitor visitor);
}
@chelseatroy
chelseatroy / bob_and_alice.scm
Created November 2, 2019 23:25
Adding Types
#lang racket
(define (attach-tag tag item)
(cons tag item))
(define (contents tagged-item)
(cdr tagged-item))
...
#lang racket
(define (make-alice-box x1 y1 x2 y2)
(cons (cons x1 y1) (cons x2 y2)))
(define (alice-width box)
(abs (- (car (cdr (box))
(car (car (box)))))
(define (alice-height box)
@chelseatroy
chelseatroy / bob_and_alice.scm
Last active November 2, 2019 23:11
Bob Box
#lang racket
(define (make-bob-box x y w h)
'bob-box (cons (cons x y) (cons w h)))
(define (bob-width box)
(car (cdr (box))))
(define (bob-height box)
(cdr (cdr (box))))
@chelseatroy
chelseatroy / bob_and_alice.scm
Created November 2, 2019 23:06
Two Box Implementations
#lang racket
(define (make-bob-box x y w h)
(attach-tag 'bob-box (cons (cons x y) (cons w h))))
(define (bob-width box)
(car (cdr (box))))
(define (bob-height box)
(cdr (cdr (box))))
@chelseatroy
chelseatroy / data.scm
Created November 2, 2019 20:36
Scheme Data
> (define pair (cons 2 3))
> pair
'(2 . 3)
> (car pair)
2
> (cdr pair)
3
@chelseatroy
chelseatroy / fun_fun_function.scm
Created November 2, 2019 17:41
Composing More Procedures
; 1.43
(define (repeated operation n)
(define (operation-iter iterator composed-function)
(if (= iterator 1)
(lambda(x) (composed-function x))
(operation-iter (- iterator 1) (compose operation composed-function))
))
(operation-iter n operation)
)