Today the Hobbyist, Tommorow, The World!

Dave Dave_member at pathlink.com
Thu May 4 11:36:30 PDT 2006


Walter Bright wrote:
> Dave wrote:
>> An idea for whatever the style outcome - post a link to something like 
>> this somewhere, or otherwise a "Sample Code" page. The idea would be 
>> to provide people in a hurry (a) nice short example(s) showing some of 
>> the primary D features. For example, I would think this would be 
>> something C++ coders could quickly scan and be intrigued by:
> 
> I think this is very good. Can I use it, or perhaps you can put it on 
> wikipedia?


Sure! I'll put it on Wikipedia too.

- Dave

>> #!/usr/bin/dmd -run
>> /* sh style script syntax is supported! */
>>
>> /* Hello World in D
>>    To compile:
>>    dmd hello.d
>>     or to optimize:
>>    dmd -O -inline -release hello.d
>> */
>>
>> import std.stdio;
>>
>> void main(char[][] args)
>> {
>>     writefln("Hello World, Reloaded");
>>
>>     // auto type inference and built-in foreach
>>     foreach(argc, argv; args)
>>     {
>>         // OOP!
>>         CmdLin cl = new CmdLin(argc, argv);
>>         // improved printf!!
>>         writefln(cl.argnum, cl.suffix, " arg: %s", cl.argv);
>>         // Garbage Collection or explicit memory management!!!
>>         delete cl;
>>     }
>>
>>     // Nested structs, classes and functions!
>>     struct specs
>>     {
>>         // all vars. automatically initialized
>>         int count, allocated;
>>     }
>>
>>     specs argspecs(char[][] args)
>>     {
>>         specs* s = new specs;
>>         // no need for '->'
>>         s.count = args.length;
>>         s.allocated = typeof(args).sizeof; // built-in properties for 
>> native types
>>         foreach(argv; args)
>>             s.allocated += argv.length * typeof(argv[0]).sizeof;
>>         return *s;
>>     }
>>
>>     // built-in string and common string operations
>>     writefln("argc = %d, " ~ "allocated = 
>> %d",argspecs(args).count,argspecs(args).allocated);
>> }
>>
>> class CmdLin
>> {
>>     private int _argc;
>>     private char[] _argv;
>>
>> public:
>>     this(int argc, char[] argv)
>>     {
>>         _argc = argc;
>>         _argv = argv;
>>     }
>>
>>     int argnum()
>>     {
>>         return _argc + 1;
>>     }
>>
>>     char[] argv()
>>     {
>>         return _argv;
>>     }
>>
>>     char[] suffix()
>>     {
>>         char[] suffix = "th";
>>         switch(_argc)
>>         {
>>         case 0:
>>             suffix = "st";
>>             break;
>>         case 1:
>>             suffix = "nd";
>>             break;
>>         case 2:
>>             suffix = "rd";
>>             break;
>>         default:
>>         }
>>         return suffix;
>>     }
>> }



More information about the Digitalmars-d mailing list