As the title implies, I don't understand the difference between using #:transparent
and using #:prefab
when defining a struct. The reference mentions that prefab involves some sort of global sharing.
What is the difference between them? In which situation should I use one over the other?
define-struct is a Racket macro that you use to define 'structure template' along with several other things.
The general syntax for a struct declaration in C is: struct tag_name { type member1; type member2; /* declare as many members as desired, but the entire structure size must be known to the compiler. */ }; Here tag_name is optional in some contexts.
To extend the other answers and give some more examples for the second part of the question:
#lang racket
(struct A (x y))
(displayln (A 1 2)) ; => #<A>
(equal? (A 1 2) (A 1 2)) ; => #f
;(equal? (A 1 2) (read (open-input-string (~a (A 1 2))))) ; => ERR: bad syntax
(struct B (x y) #:transparent)
(displayln (B 3 4)) ; => #(struct:B 3 4)
(equal? (B 3 4) (B 3 4)) ; => #t
(equal? (B 3 4) (read (open-input-string (~a (B 3 4))))) ; => #f
(struct C (x y) #:prefab)
(displayln (C 5 6)) ; => #s(C 5 6)
(equal? (C 5 6) (C 5 6)) ; => #t
(equal? (C 5 6) (read (open-input-string (~a (C 5 6))))) ; => #t
To make a structure type transparent, use the #:transparent keyword after the field-name sequence:
(struct posn (x y)
#:transparent)
> (posn 1 2)
(posn 1 2)
An instance of a transparent structure type prints like a call to the constructor, so that it shows the structures field values. A transparent structure type also allows reflective operations, such as struct? and struct-info, to be used on its instances.
Although a transparent structure type prints in a way that shows its content, the printed form of the structure cannot be used in an expression to get the structure back, unlike the printed form of a number, string, symbol, or list.
A prefab (“previously fabricated”) structure type is a built-in type that is known to the Racket printer and expression reader. Infinitely many such types exist, and they are indexed by name, field count, supertype, and other such details. The printed form of a prefab structure is similar to a vector, but it starts #s instead of just #, and the first element in the printed form is the prefab structure type’s name.
Lastly, I think you may need using #:transparent most of the time over #:prefab ,based on my experience I usually use #:transparent.
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