[racket] Example of using a struct as a port

From: Chad Albers (calbers at neomantic.com)
Date: Sat Apr 21 15:32:15 EDT 2012

Interesting...that works....but in this case, the struct is purely a port,
since it has no other fields.  an-i is not really an instance of a struct
i, but a definition that returns the value of an instance of a struct that
takes as its sole field value a port.   IOW, it doesn't take as its only
field value a string, and then use its port to output the string.

#lang racket
(struct i (x) #:property prop:input-port ((lambda (i)
                                                        (open-input-port
(struct-field-index x)))

(define an-i (i "Hello"))
(read an-i) => "Hello"

Of course, this doesn't work at all....struct-field-index x is not
available in the lambda....the only time that I have seen
struct-field-index work is when the struct's property prop:procedure is
set, and the struct suddenly becomes a procedure.

If it doesn't work as I thought, I think I'm just failing to understand the
value adding the port property to a struct, and how setting this property
makes it easier to create custom ports.

A struct as a port is a strange animal.  For instance, I can write

(struct speaker (say) #:property prop:input-port (open-input-string
"Goodbye"))
(define me (speaker "Hello"))
(display (speaker-say me)) => "Hello"
(display (read speaker)) => "Goodbye"

What would be cool, but perhaps is not possible is generating something
like:

(display (read speaker)) = "HelloGoodbye".

IOW, the port actually has access to fields in the struct.  Otherwise, I
just don't understand what the use-case is for adding the port property to
the struct.  Might as well just assign one of the struct's fields to be a
port, rather than the ceremony of setting a property on the struct.

Chad

On Sat, Apr 21, 2012 at 2:04 PM, Eric Hanchrow <eric.hanchrow at gmail.com>wrote:

> #lang racket
> (struct i (x) #:property prop:input-port 0)
> (define (an-i str) (i (open-input-string str)))
> (read (an-i "hello")) ;; yields 'hello
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20120421/76a40ee8/attachment-0001.html>

Posted on the users mailing list.