Code Comparison - Seeking D Equivalent to Lisp "dofile"

David Medlock noone at nowhere.com
Mon Feb 20 06:07:57 PST 2006


Jarrett Billingsley wrote:

> "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 ;)
> 

If you ever sit down and learn Scheme or Lisp, you will understand those 
  parentheses serve very important capabilities.  Features such as 
try/catch, conditionals, templates, type systems and many other features 
are easily added to Lisp due to its AST syntax.

Delegates equivalent to what *all* functions are in Lisp.
Templates are not needed because a Lisp macro is a function which 
accepts a Lisp program and returns a Lisp program!

Semantically its easily more powerful than D or C++, with D probably 
2-3x faster in most cases.

-DavidM



More information about the Digitalmars-d-learn mailing list