Created
March 13, 2016 08:11
-
-
Save brianclements/6030d87d0dfb082b50b4 to your computer and use it in GitHub Desktop.
understanding boxes and pass-by-value in racket
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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)) |
Author
brianclements
commented
Mar 13, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment