[Prev][Next][Index][Thread]

Re: Critique this macro, please



On Wed, 20 Dec 2000 10:53:54 +0000, Jason Trenouth <jason@harlequin.co.uk>
wrote:

> BTW I don't think that this is idiomatic Dylan. I'd prefer a macro as follows
> (renamed to be more self-documenting):
> 
>   define macro with-each-line
>     { with-each-line ( ?line:name = ?file:expression ) ?body:body end }
>     =>
>     { // capture ?body in method with ?line as parameter and call
>       // on each line read from ?file }
>   end macro;
> 
> then use it as follows:
> 
>   with-each-line ( line = "foo.txt )
>     parse-foo( line );
>   end;
> 
> Quite often macro designers arrange for their macro eg "with-each-line" to
> expand into a function which takes the captured a body of code in a closure. 
> 

OR another approach to abstracting this would be to define a new
<file-sequence> class that allowed you to iterate of the lines in a file:

  with-file-sequence ( file = "foo.txt", delimiter: '\n' )
    for ( line in file )
      parse-foo( line );
    end;
  end;

You just have to define an iteration protocol for your new class that reads
successive delimited objects (eg lines) from the file. By making an adapter
from file+streams to sequences you can then use all your favourite sequence
methods on them, eg:

  with-file-sequence ( file = "foo.txt", delimiter: '\n' )
    position( file, "bar", test: string= );
  end;

Finds the line number of the line matching "bar".

BTW The implementation should probably specialize "stream-contents" for getting
the sequence from the stream.

A <sequence-stream> is the inverse adapter, which lets <sequence>s be treated
as <stream>s.

__Jason


Follow-Ups: References: