Docsity

Implementing Variables and Call-by-Reference in BCFAE Interpreter - Prof. Matt Flatt, Study notes of Programming Languages

Partial preview of the text

Download Implementing Variables and Call-by-Reference in BCFAE Interpreter - Prof. Matt Flatt and more Study notes Programming Languages in PDF only on Docsity!

1

Page 1

2

Store-Passing Interpreters

Our^ BCFAE^ interpreter explains state by representing the store as avalue• Every step in computation produces a new store• The interpreter itself is purely functionalIt's a^ store-passing interpreter

4

Variables

Boxes don't explain one of our earlier Scheme examples:^ (define

counter^0 ) (define (f^ x) (begin (set!^ counter^ (+^

x^ counter))

counter))

In a program like this, an identifier no longer stands for a

value ;

instead, an identifier stands for a

variable

5

BMCFAE = BCFAE + variables ::=^ | {+^ ^

}

|^ {-^

}

|^ |^ {fun^ {}

}

|^ {^

|^ {if0^

^

|^ {newbox^

|^ {setbox^

}

|^ {openbox^

|^ {seqn^

}

|^ {set^ ^

NEW^8

Implementing Variables (define-type^ DefrdSub^ [mtSub]^ [aSub^ (name^ symbol?

) (address integer?) (ds DefrdSub?)])

9

Implementing Variables

;^ interp^ :^ BCFAE^ DefrdSub

Store^ ->^ Value*Store (define^ (interp^ expr

ds^ st) ... [app^ (fun-expr^ arg-expr

(interp-two^ fun-expr

arg-expr^ ds^ st (lambda (fun-val^ arg-val^ st

(local^ [(define^ a^

(malloc^ st))] (interp (closureV-body^ fun-val) (aSub (closureV-param^ fun-val

a (closureV-sc^ fun-val

(aSto^ a arg-val^ st)))))] ...)

11-

Implementing Variables

;^ interp^ :^ BCFAE^ DefrdSub

Store^ ->^ Value*Store (define^ (interp^ expr

ds^ st) ... [set^ (id^ val-expr) (local^ [(define

a^ (lookup^ id^ ds))] (type-case Store*Value^ (interp^

val-expr^ ds^ st) [vs^ (val^ st) (vs^ val^ (aSto^ a val^ st

))]))]

17-

Call-by-Reference

What if we wanted

swap^ to change^ a

(define^ (swap^ x^ y)^ (local^ [(define^

z^ y)] (set! y x) (set! x z))) (local^ [(define^ a^

⇒^ (define 10 ) (define b 20 )] (begin (swap a b) a))

(swap^ x^ y) (local^ [(define^ z^ (box^

(unbox^ y)))] (set-box!^ y^ (unbox

x)) (set-box!^ x^ (unbox

z)))) (local^ [(define^ a^

(box^10 ))(define b (box^20 ))] (begin ;(swap (box (unbox^ a));(box (unbox^ b))) (swap a b) (unbox a)))

This is called^ call-by-reference

, as opposed to^ call-by-value

Terminology alert:^ this “call-by-value” is orthogonal to the use in“call-by-value” vs. “call-by-name”

23

Implementing Call-by-Reference ; interp : BCFAE^ DefrdSub^ Store^ ->

Value*Store (define^ (interp^ expr

ds^ st) ... [app^ (fun-expr^ arg-expr

(if^ (id?^ arg-expr) ;^ call-by-ref^

handling^ for^ id^ arg: (type-case Value*Store^ (interp^ fun-expr

ds^ st) [v*s^ (fun-val^ st) (local^ [(define

a (lookup^ (id-name^ arg-expr

)^ ds))] (interp^ (closureV-body

fun-val) (aSub namea (closureV-sc^ fun-val)) st))]) ;^ as^ before: ...)] ...)

24