Flux
Flux

Reputation: 10920

How to include field names when printing a Racket struct

Suppose I have this Racket code:

(struct pos (x y))
(displayln (pos 5 6))

This displays #<pos>. Is there a way to make it display the field names and values too?

With the #:transparent option, the values are displayed:

(struct pos (x y) #:transparent)
(displayln (pos 5 6))

This displays #(struct:pos 5 6), but I also want to display the field names (x and y). Is there a way to display both the field names and values? For example: #(struct:pos #:x 5 #:y 6).

I am looking for something similar to how Common Lisp structs are displayed. Common Lisp example:

(defstruct pos x y)
(format t "~A~%" (make-pos :x 5 :y 6))

This prints #S(POS :X 5 :Y 6).

Upvotes: 0

Views: 157

Answers (1)

Sorawee Porncharoenwase
Sorawee Porncharoenwase

Reputation: 6502

If you don't want to use third-party libraries, take a look at the very last example of make-constructor-style-printer.

If you don't mind using third-party libraries, you can just use Rebellion's record.

Upvotes: 1

Related Questions