Code Comparison - Seeking D Equivalent to Lisp "dofile"
Tony
ignorethis at nowhere.com
Sat Feb 18 22:46:20 PST 2006
"Jarrett Billingsley" <kb3ctd2 at yahoo.com> wrote in message
news:dt8tee$uq6$1 at digitaldaemon.com...
> "Tony" <ignorethis at nowhere.com> wrote in message
> news:dt8rlm$nvn$1 at digitaldaemon.com...
>> I'm torn between D and Lisp.
>
> That someone could ever say that just.. blows my mind :)
>
>> In order to compare the two, I was wondering if anyone could provide me
>> with the D equivalent of the following Lisp macro "dofile".
>>
>> dofile allows code such as the following to be written:
>>
>> (dofile (line "path-to-file")
>> (do-something-with-each-line))
>>
>> For example:
>>
>> (dofile (line "c:/myfile.txt")
>> (print line))
>>
>> The above code would open the (text only) file, print each line and then
>> close the file. It should be noted that the body of the dofile is not
>> limited to one expression (it can contain any number of expressions).
>>
>> In case anyone is interested, here is the Lisp code for dofile:
>>
>> (defmacro dofile ((line file-path) &body body)
>> (let ((in-stream (gensym "IN-STREAM-")))
>> `(with-open-file (,in-stream ,file-path :direction :input
>> :if-does-not-exist nil)
>> (if (eql ,in-stream nil)
>> nil
>> (do ((,line (read-line ,in-stream nil) (read-line ,in-stream
>> nil)))
>> ((null ,line) t)
>> , at body)))))
>
> import std.stream;
>
> ...
>
> File f = new File(`c:\myfile.txt`, FileMode.In);
> foreach(char[] line; f)
> writefln(line);
>
> How about that? Not bad. And certainly more readable than your little
> sea of parentheses you've got there ;)
>
> Or, if you're feeling a little more adventurous, you can take advantage of
> D's function/delegate literals:
>
> void dofile(char[] fileName, void delegate(char[] line) dg)
> {
> // Note the "auto" - the file will be automatically closed when the
> // function returns.
> auto File f = new File(fileName, FileMode.In);
>
> foreach(char[] line; f)
> dg(line);
> }
>
> ...
>
> dofile(`c:\myfile.txt`,
> delegate void(char[] line)
> {
> writefln(line);
> }
> );
Thanks Jarrett.
Your dofile function seems to have most of the functionality of the Lisp
macro. And I'm forced to admit that it is a little more readable than my
"little sea of parentheses" :)
I would have to say that D comes out ahead in this particular instance.
Tony
Melbourne, Australia
tonysZ-mailboxZ at hotmailZ.com (remove the Zs)
More information about the Digitalmars-d-learn
mailing list