Skip to content

Instantly share code, notes, and snippets.

@brianclements
Created March 13, 2016 08:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianclements/6030d87d0dfb082b50b4 to your computer and use it in GitHub Desktop.
Save brianclements/6030d87d0dfb082b50b4 to your computer and use it in GitHub Desktop.
understanding boxes and pass-by-value in racket
#lang racket
(define a 'one)
(printf "var 'a' is '~a'\n\n" a)
(define (foo x)
(printf "we call '(foo)' here and pass it '2'\n")
(printf "(foo) sets 'x'\n")
(printf "->arg 'x' is '~a'\n" x)
(set! x 'changed)
(printf "->arg 'x' in this closure now is '~a'\n\n" x))
(foo 2)
(printf "but var 'a' in top level is still '~a'\n\n" a)
(define (foo2 x)
(printf "we now pass var 'a' as arg 'x' in (foo2): 'x' is '~a'\n" x)
(printf "(foo) sets 'x'\n")
(set! x 'changed)
(printf "->arg x now is '~a' in this closure as well...\n\n" x))
(foo2 a)
(printf "...but var 'a' is still '~a' because it's passed by value\n\n" a)
(define b (box 'two))
(printf "'b' is a box, it's value is: '~a'\n\n" (unbox b))
(define (new-foo x)
(printf "we now pass box 'b' as arg 'x' in (new-foo): 'x' is '~a'\n" (unbox x))
(printf "(new-foo) sets 'x'\n")
(set-box! x 'changed)
(printf "->arg 'x' in this closure now is '~a'...\n\n" (unbox x)))
(new-foo b)
(printf "...but so is our top level box 'b'!: '~a'\n\n" (unbox b))
@brianclements
Copy link
Author

var 'a' is 'one'

we call '(foo)' here and pass it '2'
(foo) sets 'x'
->arg 'x' is '2'
->arg 'x' in this closure now is 'changed'

but var 'a' in top level is still 'one'

we now pass var 'a' as arg 'x' in (foo2): 'x' is 'one'
(foo) sets 'x'
->arg x now is 'changed' in this closure as well...

...but var 'a' is still 'one' because it's passed by value

'b' is a box, it's value is: 'two'

we now pass box 'b' as arg 'x' in (new-foo): 'x' is 'two'
(new-foo) sets 'x'
->arg 'x' in this closure now is 'changed'...

...but so is our top level box 'b'!: 'changed'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment