Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print Racket structs

Tags:

racket

Is there any way to control how a struct is printed?

For example if I have a transparent struct containing an image:

(struct photo (label image-data) #:transparent)

But I don't want to print the image-data field.

like image 929
Ben Greenman Avatar asked Sep 20 '16 19:09

Ben Greenman


People also ask

How do you print a new line in a racquet?

~n or ~% prints a newline character (which is equivalent to \n in a literal format string)

What is a struct in racket?

Programmer-Defined Datatypes in The Racket Guide introduces structure types via struct. A structure type is a record datatype composing a number of fields. A structure, an instance of a structure type, is a first-class value that contains a value for each field of the structure type.


2 Answers

I want to extend Ben's answer a bit. You can also combine gen:custom-write with make-constructor-style-printer to make the struct printing significantly easier. This function handles the differences between printing, writing, quote depth, and output port for you.

Extending his example gives:

#lang racket
(require pict
         racket/struct)

(struct photo (label image-data)
  #:transparent
  #:methods gen:custom-write
  [(define write-proc
     (make-constructor-style-printer
       (lambda (obj) 'photo)
       (lambda (obj) (list (photo-label obj)))))])

(displayln (photo "fish" (standard-fish 100 100)))
;; Prints #<photo: fish>

(println (photo "fish" (standard-fish 100 100)))
;; Prints (photo "fish")

Now write, display, and print all work as you would expect

like image 59
Leif Andersen Avatar answered Nov 08 '22 09:11

Leif Andersen


Yes! Use the gen:custom-write generic interface.

#lang racket
(require pict)

(struct photo (label image-data)
  #:transparent
  #:methods gen:custom-write
  [(define (write-proc photo-val output-port output-mode)
     (fprintf output-port "#<photo:~a>" (photo-label photo-val)))])

(photo "fish" (standard-fish 100 100))
;; Prints "#<photo:fish>"

The first argument to write-proc is the struct to be printed. The second argument is the port to print to. The third argument suggests how the context wants the value printed, see the docs: http://docs.racket-lang.org/reference/Printer_Extension.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._gen~3acustom-write%29%29

like image 29
Ben Greenman Avatar answered Nov 08 '22 07:11

Ben Greenman