Pointers in Scheme
In Scheme, we don’t have direct pointer manipulation like in lower-level languages. However, we can demonstrate similar concepts using mutable data structures and procedure arguments.
; We'll show how mutable data works in contrast to values with
; 2 procedures: 'zeroval' and 'zeroptr'. 'zeroval' has a
; number parameter, so arguments will be passed to it by
; value. 'zeroval' will get a copy of 'ival' distinct
; from the one in the calling procedure.
(define (zeroval ival)
(set! ival 0))
; 'zeroptr' in contrast takes a mutable box (similar to a pointer).
; The 'set-box!' procedure then changes the value inside the box.
; This is analogous to dereferencing and modifying a pointer.
(define (zeroptr iptr)
(set-box! iptr 0))
(define (main)
(let ((i (box 1)))
(display "initial: ")
(display (unbox i))
(newline)
(zeroval (unbox i))
(display "zeroval: ")
(display (unbox i))
(newline)
; We pass the box directly to 'zeroptr'
(zeroptr i)
(display "zeroptr: ")
(display (unbox i))
(newline)
; In Scheme, we don't typically print memory addresses,
; but we can show that 'i' is a box
(display "is-box: ")
(display (box? i))
(newline)))
(main)
To run this Scheme program, save it to a file (e.g., pointers.scm
) and run it using a Scheme interpreter. For example, if you’re using Chez Scheme:
$ scheme --script pointers.scm
initial: 1
zeroval: 1
zeroptr: 0
is-box: #t
In this Scheme version:
We use a box (created with
box
) to simulate a pointer. A box is a mutable container that can hold a single value.zeroval
takes a value and tries to set it to 0, but this doesn’t affect the original value because Scheme uses pass-by-value for simple data types.zeroptr
takes a box and usesset-box!
to change the value inside the box, which is analogous to dereferencing and modifying a pointer.In the
main
procedure, we create a box containing 1, then demonstrate howzeroval
doesn’t change the boxed value, butzeroptr
does.Instead of printing a memory address, we show that
i
is indeed a box using thebox?
predicate.
This example demonstrates how Scheme handles mutable state and illustrates a concept similar to pointers, even though Scheme doesn’t have direct pointer manipulation like lower-level languages.