When I print in Racket, only the type is printed of structures, not the value. (I'm working in DrRacket, in the interactions area.)
For example, I have a tree structure:
#lang racket
(define-struct node [name left right])
An example could be:
(define SALLY (make-node 'sally BOBBY SUSIE))
(define BOBBY (make-node 'bobby NONE NONE))
(define SUSIE (make-node 'susie NONE NONE))
What I see:
> (print SALLY)
#<node>
What I want to see:
> (print SALLY)
(make-node 'sally (make-node 'bobby NONE NONE)
(make-node 'susie NONE NONE))
How can I see the value and not the type?
Use #:transparent
keyword:
(define-struct node [name left right] #:transparent)
> (define-struct node [name left right] #:transparent)
> (define NONE '())
> (define BOBBY (make-node 'bobby NONE NONE))
> (define SUSIE (make-node 'susie NONE NONE))
> (define SALLY (make-node 'sally BOBBY SUSIE))
> (print SALLY)
(node 'sally (node 'bobby '() '()) (node 'susie '() '()))
NB: Today struct
is preferred over define-struct
so I've written the code with struct
.
It doesn't really print the type but it's the default representation of the object. There are two options you can do:
1. Use #:transparent
keyword.
(struct node [name left right] #:transparent)
(define root (node 'd
(node 'b (node 'a '() '())
(node 'c '() '()))
(node 'f (node 'e '() '())
(node 'g '() '()))))
root ; ==>
; (node 'd
; (node 'b (node 'a '() '())
; (node 'c '() '()))
; (node 'f (node 'e '() '())
; (node 'g '() '()))))
Notice how they look like the construction?
1. Add a writer for the object
(struct node [name left right]
#:methods gen:custom-write
[;; needs to be named write-proc
(define (write-proc x port mode)
((if (eq? mode #t) write display) (fancy-writer x 0) port))
;; helper used by write-proc
(define (fancy-writer x ident)
(if (null? x)
""
(let ([new-ident (+ 5 ident)])
(string-append (fancy-writer (node-left x) new-ident)
(string-append (make-string ident #\space)
(symbol->string (node-name x))
"\n")
(fancy-writer (node-right x) new-ident)))))])
root ; ==>
; a
; b
; c
; d
; e
; f
; g
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With