[racket] Example of using a struct as a port

From: Eric Hanchrow (eric.hanchrow at gmail.com)
Date: Sat Apr 21 14:04:41 EDT 2012

How about

#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


?

On Sat, Apr 21, 2012 at 9:43 AM, Chad Albers <calbers at neomantic.com> wrote:
> I was thinking more along the lines of:
>
> #lang racket
> (struct i (x) #:property prop:input-port 0)
> (define an-i (i "hello"))
> (read an-i) ;; yields 'hello
>
> I know this doesn't work.  IOW, the read operation actually has accesses to
> a field inside the struct itself.  If that's impossible, then I'm trying to
> understand why structs could be treated like ports, but then the data in the
> port doesn't really have access to the field-values in the struct.
>
> Thanks for your help,
> --
> Chad
>
>
>
>
> On Sat, Apr 21, 2012 at 12:35 PM, Matthias Felleisen <matthias at ccs.neu.edu>
> wrote:
>>
>>
>> On Apr 21, 2012, at 11:52 AM, Chad Albers wrote:
>>
>> Hi,
>>
>> I'm looking for an example of treating a struct like a port, which appears
>> to be
>> possible: http://docs.racket-lang.org/reference/portstructs.html?q=struct#(def._((quote._~23~25kernel)._prop~3ainput-port))
>>
>> Apparently, this is a lot easier that using make-custom-port.   What I
>> would like to do is be able to declare a struct, set it's prop:input-port
>> property, pass an instance of struct to a port procedure, like (read-bytes
>> string-that-acts-like-port), and have the bytes sent to the read-bytes
>> actually contain bytes that were stored in the fields of the struct itself.
>>  Is that possible, and is that the reason why one would treat a struct like
>> a port?
>>
>> Thanks in advance for any examples,
>>
>>
>>
>> Do you mean something like this:
>>
>> #lang racket
>> (struct i (x) #:property prop:input-port 0)
>> (define an-i (i (open-input-string "hello world")))
>> (read an-i) ;; yields 'hello
>>
>> -- Matthias
>>
>
>
> ____________________
>  Racket Users list:
>  http://lists.racket-lang.org/users
>


Posted on the users mailing list.