Warning: This is a long page. Please be patient waiting for it to load. If page fails to load due to a time-out error, please try again later (when the server may be less busy).

Categories





Examples

Fundamentals

It Compiles

DescriptionIt doesn't actually do anything, but it compiles and runs.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
void main()
{
}
For an explanation of what this means, visit Wiki4D.
 

Do Something

DescriptionIt's an abbreviated "hello world" without the world.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
void main()
{ 
    printf("Hi");
}

Prints "Hi" at the command line.

The printf function is an easy way to send text to the console window. In this example, the quoted phrase is simply printed in the console window.

See more examples on using printf are at Wiki4D.

 

Initializing Variables

DescriptionShows how to initialize an integer and a string.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
int magicNumber = 42;

char[] password = "sesame";

void main()
{
    printf("Magic number: %d\n", magicNumber);
    printf("Password: %.*s\n", password);
}
 

Data Types

DescriptionShows how sizeof and max can reveal the size and possible maximum value of data types.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
int main() 
{
    // Show information about integer types...
    printf("bit\tmin: %d\tmax: %d (%u)\n", bit.min, bit.max, bit.sizeof);  
    printf("ubyte\tmin: %u\tmax: %u (%u)\n", ubyte.min, ubyte.max, ubyte.sizeof);  
    printf("ushort\tmin: %u\tmax: %u (%u)\n", ushort.min, ushort.max, ushort.sizeof);  
    printf("uint\tmin: %u\tmax: %u (%u)\n", uint.min, uint.max, uint.sizeof);  
    printf("ulong\tmin: %llu\tmax: %llu (%u)\n", ulong.min, ulong.max, ulong.sizeof);    
    printf("byte\tmin: %d\tmax: %d (%u)\n", byte.min, byte.max, byte.sizeof);  
    printf("short\tmin: %d\tmax: %d (%u)\n", short.min, short.max, short.sizeof);    
    printf("int\tmin: %d\tmax: %d (%u)\n", int.min, int.max, int.sizeof);    
    printf("long\tmin: %lld\tmax: %lld (%u)\n", long.min, long.max, long.sizeof);    

    // Show information about floating-point types...
    printf("float (%u)\tdouble (%u)\treal (%u)\t", float.sizeof, double.sizeof, real.sizeof);
    printf("ifloat (%u)\tidouble (%u)\tireal (%u)\t", ifloat.sizeof, idouble.sizeof, ireal.sizeof);
    printf("cfloat (%u)\tcdouble (%u)\tcreal (%u)\t", cfloat.sizeof, cdouble.sizeof, creal.sizeof);
    printf("cfloat (%u)\tcdouble (%u)\tcreal (%u)\t", cfloat.sizeof, cdouble.sizeof, creal.sizeof);

    // Show information about character types...
    printf("char (%u)\twchar (%u)\tdchar (%u)\t", char.sizeof, wchar.sizeof, dchar.sizeof);


    /* 

    *** sizeof vs. size ***

    Currently the sizeof and size attributes act the same way (and carry the same role). 
    Since this is extremely redundant, it's safe to assume that only one of these will 
    remain in D. Walter has indicated that he prefers sizeof since it's already a keyword 
    in C that is used in a similar fashion. I'd recommended using sizeof rather than size.

    */

    return 0;

}

I'm trying to start with the basics: whole numbers. The above code will show the upper and lower limits for the integer data types in D and sizes for other data types. It's pretty fancy, so hopefully I'm doing this right. I make use of the min and max attributes.

Output

bit min: 0 max: 1 (1)
ubyte min: 0 max: 255 (1)
ushort min: 0 max: 65535 (2)
uint min: 0 max: 4294967295 (4)
ulong min: 0 max: 18446744073709551615 (8)
byte min: -128 max: 127 (1)
short min: -32768 max: 32767 (2)
int min: -2147483648 max: 2147483647 (4)
long min: -9223372036854775808 max: 9223372036854775807 (8)
float (4) double (8) real (10) ifloat (4) idouble (8)
ireal (10) cfloat (8) cdouble (16) creal (20) cfloat (8)
cdouble (16) creal (20) char (1) wchar (2) dchar (4)

Integer Types

TypeMinMaxSize (bytes)
bit 0 11
ubyte 0 2551
ushort 0 65,5352
uint 0 4,294,967,2954
ulong 0 18,446,744,073,709,551,6158
byte -128 1271
short -32,768 32,7672
int -2,147,483,648 2,147,483,6474
long -9,223,372,036,854,775,808 9,223,372,036,854,775,8078

Floating-Point Types

  • Floating point:
    • float
    • double
    • real
  • Complex and Imaginary:
    • cfloat
    • cdouble
    • creal
  • Complex and Imaginary:
    • ifloat
    • idouble
    • ireal

Character Types

  • char: unsigned 8 bit (UTF-8)
  • wchar: unsigned 16 bit (UTF-16)
  • dchar: unsigned 32 bit (UTF-32)

The official list is in the D Specification, of course.

 

If/Else

DescriptionSimple (yet effective) flow control.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
void main()
{
    int i;
    if(i==0) printf("It's one!"); else printf("It's not one!");
}
 

The "for" Loop

DescriptionHow to do the same thing over and over again.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
int main()

{   
   for (int i=1; i<=10; i++)
   {
      printf("%d\n", i);
   }
   return 0;

}
 

Variables

DescriptionCreating "slots" to store data.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
void main()
{
    int myInt;
    int myint;
    int MYINT;
}

Declare three separate integer variable called myInt, myint, and MYINT.

Like many things in D, variable declarations are a lot like C, C++, and Java.

In D, all variables have to be declared before they are used..

Some Facts About Identifiers
  1. Identifiers must begin with a letter.
  2. Subsequent characters can be numbers or underscores as well as additional letters.
  3. Identifiers can be as long as you want.
  4. Note that variable identifiers in D are case-sensitive. (In the above example, "myInt", "myint", and "MYINT" are separate identifiers.)
 

Expressions

DescriptionDemonstrates using mathematical expressions.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
import std.c.stdio; /* for using printf */


void main()
{
    int i, j;


    i = 12 * 12; /* multiplication */
    printf("12 x 12 = %d\n", i); /* i should be 144 */

    j = i / 8; /* division */
    printf("144 / 8 = %d\n", j); /* j should be 18 */

    i -= 44; /* same as saying "i = i - 44;" */
    printf("144 - 44 = %d\n", i); /* i should be 100 */

}
 

Comments

DescriptionGood documentation is a good idea.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7

There are three types of comments in D:

  1. Line comments: //
  2. Block comments: /* */
  3. Nested comments: /+ +/

Line Comments

Line comments begin with // and continue until the end of the line. The comment automatically ends at the end of the line, so make sure the next line is valid code. If you want a multiple-line comment, then use a block comment or a nested comment. (If your code gets word-wrapped, your code would break, but you probably should try avoiding editors that word-wrap your code anyways.)

If you're familiar with modern flavors of BASIC, // is equivalent to a '.

Block Comments

Block comments can exist entirely a line or contain multiple lines of commentary. Block comments begin with a /* and end with a */. If you forget a matching closing symbol, your code will either do something you didn't expect, or it won't compile at all. Block comments don't nest. If you want nesting comments, then use nested comments.

Nested Comments

Nested comments can exist entirely a line or contain multiple lines of commentary. Nested comments begin with a /+ and end with a +/. Just like block comments, openning comment markers must be matched with closing marks.

These comments do nest so that you can put one inside another. The most obvious use for this feature is to "comment out" code that you don't want to compile right now (because you're not sure if it's any good) but might be valuable code. Of course, once you decide it's garbage, you'd want to delete the whole passage. Nested comments are a little more complicated than single-line or block comments, so they aren't used in the in this fairly simple example included below.

/* 
comments.html 
Author: J C Calvarese
License: public domain

This program demonstrates using comments in D.
(Such as the multi-line comment this sentence resides in.)
*/

import std.c.stdio; // This is the module that allows us to use printf later...

/*   
    This is another block (or multiline) comment.  
*/

int main()  
{ 
     /* The main function is where the action starts in D. */
    
    printf("This program is documented.\n"); // This command prints some text...
    
    // "printf"" is actually a C command. 
        
    // This is a single line comment.  It automatically ends at the end of the line.

    return /* 0 is an int */ 0;

    
    /* 
        since main is supposed to return an int ("integer"), 
        the above command is required... 
    */ 
}
 

String Comparison Operators

DescriptionShows how strings are compared.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
/*

Title:      String Operations
File:       string_ops.d
Author:     J C Calvarese, http://jcc_7.tripod.com/d/
Date:       2003/10/07
License:    Public Domain

*/


int main()
{
    char[] str1 = "Aardvark";
    char[] str2 = "Zebra";
    char[] str3 = "1";
    
    
    /* "less than" operator */
    
    if ( str1 < str2 ) 
      printf("Aardvark comes before Zebra.\n");
    else
      printf("Aardvark comes after Zebra.\n");
    
    
    /* "greater" than operator */
    
    if ( str1 > str2 ) 
      printf("Aardvark comes after Zebra.\n");
    else
      printf("Aardvark comes before Zebra.\n");
    
    
    /* "equality" operator */
    
    if ( str1 == str2 ) 
      printf("Aardvark is Zebra?!\n");
    else
      printf("Aardvark is NOT Zebra.\n");
    
    
    /* "concatenation" operator */
    
    for (int i=0; i<3; i++) 
      str3 ~= "0";
    printf("%.*s\n", str3);
    
    return 0;


}
 

Wait

DescriptionDemonstrates several ways to wait for the user to press a key. (Designed for Windows).
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
import std.c.stdio; /* for getch() */
import std.stream; /* for stdin */

extern (C) int system (char *);

void main()
{ 
    printf("Press a key (using 'std.c.stdio.getch();' to wait) . . .\n\0");
    getch();
    
    printf("Press another key (using 'std.stream.stdin.getch();') . . .\n\0");
    std.stream.stdin.getch();
    
    printf("Waiting again\n(using 'system(\"pause\");'):\n\0");
    system("pause");
}
 

Get a number from the user (uses scanf)

DescriptionShows how you can ask the user for a number during runtime.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
/* License: Public Domain */

import std.c.stdio; /* for scanf */
import std.stdio; /* for writef/writefln */

int main()
{
    double n;

    writef("Pick a number: ");
    scanf("%lf", &n);

    writefln("You picked: %s", n);

    return 0;

}
 

Quadratic Equation (getting input and doing calculations)

DescriptionThis program will calculate the real roots for a user-specified quadratic equation.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
/* License: Public Domain */

import std.c.stdio; /* for scanf */
import std.stdio; /* for writef/writefln */
import std.math; /* for sqrt */


int main()
{
    double a, b, c, d;

    writefln("For the equation: ax^2 + bx + c = 0");

    writef("What is a? ");
    scanf("%lf", &a);

    writef("What is b? ");
    scanf("%lf", &b);

    writef("What is c? ");
    scanf("%lf", &c);

    writefln("\nFor a = %s, b = %s, c = %s:", a, b, c);


    d = (b*b) - (4*a*c);

    if (d < 0)   
        writefln("There are no real roots.");
    else
    {
        double r1, r2;

        r1 = (-b - sqrt ( d )) / (2*a);
        r2 = (-b + sqrt ( d )) / (2*a);

        if(r1 == r2)
            writefln("Root: %s", r1);
        else
            writefln("Roots: %s, %s", r1, r2);
    }
    return 0;



    /* 

    For the quadratic equation: ax^2 + bx + c = 0
    Roots =  (-b +/- sqrt ( b^2 - 4ac )) / 2a

    For example:
    a = 1, b = -5, c = 6 
    The roots are 2 and 3.

    */

}
 

Function

DescriptionUsing a function, you can code it once and then call it when you need it, wherever you need it.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
uint squareIt(uint x)
{
    return x * x;
}


void main()
{
    int i;
    printf("%d\t(initial value)\n", i);


    i = squareIt(3);
    printf("%d\t(3 * 3)\n", i);

    i = squareIt(4);
    printf("%d\t(4 * 4)\n", i);

    i = squareIt(5);
    printf("%d\t(5 * 5)\n", i);
}
 

Nested Functions

DescriptionNested functions allows you to structure functions in a clever way if that's how your mind works.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
/*

    File:       nested.d
    Author:     J C Calvarese, http://jcc_7.tripod.com/d/
    License:    Public Domain
    Purpose:    To show how nested functions work in D.

See also the D Specification.

*/




int main(char[][] Args)
{
    int i;

    void runIt()
    {
        /* 
            This is a nested function.
            You can make use of variables
            declared in the outer function,
            but each has to be declared above
            the location of the nested function
            if you use it.
        */
    
        printf("%d\tdo something\t", i);

    }


    bit found;

    while (!found)
    {

        if(i==0)


        {
            printf("not found\t");
            runIt();
            return 0;


        }
        found = true;

    }

    return 0;


}
 

Struct

DescriptionStructs allow you to bind together basic data types into a more complicated paradigm.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
import std.c.stdio;


struct Vehicle
{  
    double cost;
    int wheels;
}


struct Utensil
{ 
    bit pointy;
    bit tined;  
}



void main()
{  
    
    Vehicle car;
    car.cost = 20_000;
    car.wheels = 4;
    
    Vehicle motorcycle;
    motorcycle.cost = 2_000;
    motorcycle.wheels = 2;
    
    Vehicle boat;
    boat.cost = 5_000; 
    boat.wheels = 0;


    Utensil spoon;
    spoon.pointy = false;
    spoon.tined = false;
    
    Utensil fork;
    fork.pointy = true;
    fork.tined = true;
    
    Utensil knife;
    knife.pointy = true;
    knife.tined = false;
}
 

Struct Initialization

DescriptionShows a quick way to initialize a struct.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
/*
From: Vathix
Subject: Re: new struct initializer syntax
Date: Fri, 30 Jan 2004 06:42:53 -0500
Xref: digitalmars.com D:22815
http://www.digitalmars.com/drn-bin/wwwnews?D/22815
*/

struct Foo
{
    int bar, baz, bam;
}

void main()
{

static Foo[] myfoo =  [
    { 0, 1, 2 },
    { bar: 3, baz: 4, bam: 5 },
    { bam: 8, baz: 7, bar: 6 },
];

}
 

Class

DescriptionA class is a similiar idea to a struct, but allows more abstract designs.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
import std.c.stdio;


class Television
{ 
    
    void pressPowerButton()
    {
        if(m_turnedOn)
            printf("It was on, but now you turned it off.\n");  
        else
            printf("Now, it's turned on (channel %d).\n", m_channel);
        m_turnedOn = !m_turnedOn;
    }
    
    void changeChannel(int c)
    {  
        if(m_turnedOn)
        {
            if(c == m_channel)
                printf("It's already on channel %d, silly.\n", m_channel);
            else
            { 
                printf("Per your request, it's now on channel %d.\n", m_channel);
                m_channel = c;
            }
        }
        else
            printf("Hmm... the TV's off. Try turning it on before you pick a channel.\n", m_channel);
                
    }
    
    this()
    {
        m_turnedOn = false;  
        m_channel = 3;
        printf("\n(Creating this object is kind of like plugging in a TV set.)\n\n");
    }
    
    ~this()
    { 
        printf("\n(Destroying this object is kind of like unplugging a TV set.)\n\n");
    }
    
    private
    {  
        bit m_turnedOn;
        int m_channel;
    }
}


void main()
{ 
    
    Television BigScreen = new Television();
    
    BigScreen.pressPowerButton();
    BigScreen.changeChannel(44);
    BigScreen.changeChannel(49);
    BigScreen.changeChannel(49);
    BigScreen.pressPowerButton();
    BigScreen.changeChannel(34);
    BigScreen.pressPowerButton();
    BigScreen.changeChannel(34);
    BigScreen.changeChannel(49);
    BigScreen.pressPowerButton();
    
    delete BigScreen;
}
 

Appending

DescriptionShows how appending works with D dynamic strings.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
void main()
{
    char[] s;
    printf("Length: %d\tString: '%.*s'\n", s.length, s);

    s ~= "something ";
    printf("Length: %d\tString: '%.*s'\n", s.length, s);

    s ~= "whatever";
    printf("Length: %d\tString: '%.*s'\n", s.length, s);
}
 

Assertions

DescriptionIf you can determine it's wrong at compile-time, why bother running it?
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
/*
 
    File:       assert.d
    Author:     Justin C. Calvarese, http://jcc_7.tripod.com/d/
    License:    Public Domain
    Purpose:    Demonstrates what an assertion does in D.

     See also the D Specification (http://www.digitalmars.com/d/expression.html#assertexpression).

*/
 


void main()
{  

    printf("Let's test some assertions...\n");

    /* These assertions should succeed --
       they evaluate to true. */

    assert(true);
    assert('\xAA' == '\u00AA');
    assert(221 % 5 == 1);
    assert(25 * 4 * 20 + 4 == 2004);
    
    /*  
        This assertion fails... 
        Error: AssertError Failure assert.d(line number) 
    */
    
    assert(false);
    
    printf("\nNo problem, man.\n");
}
 

Unittests

DescriptionUnittests let you find the bugs before you even run the program.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
module unittests;

void main()
{
    printf("test\n");
    /* This assertion will fail. */
    assert(false);  

    /* 
        The line number (7) may be different, but this is the 
        error message which should appear...
        Error: AssertError Failure unittests(7)
    */

}


class Whatever
{
   
    unittest
    
    {
        /*  unittests seem to be run in the order they appear in the code, i.e. since 
            the Whatever class appears before the module unittests, these are run first. 

            The -unittests flag has to be used to compile this program or else this code is ignored.
        

            This sample batch file compiles the code (including unittests) and then runs the executable.

            @echo off
            dmd unittests.d -unittest && unittests.exe
            pause
        */

        printf("class Whatever UnitTest...\n");
        /* If the expession of an assert doesn't evaluate to true, an exception is thrown at run-time. */

        assert(true==1);
        assert(true);
        assert(false==false);
        assert(!false);
    }
}


unittest
{
    printf("module UnitTest...\n");
    assert(true==1);
    assert(true);
    assert(false==false);
}
 

Getch/Getchar

DescriptionGet a character from the keyboard.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
import std.c.stdio;
import std.string;



void main()
{ 
    char k;

    printf("\nI'm going to ask you to press 10 keys (I promise it's painless).\n"
    "Certain keys don't count, but the whole alphabet is fair game.\n\n");

    for(int i=0; i<10; i++)
    {
        version(Windows)
        {
            printf("Press key: %d\t", i);
            k = getch();
        }
        version(Linux)
        {
            printf("Press key (follow with return): %d\t", i);
            k = getchar();
        }
        printf("[%c]\t", k);            /* print the character pressed */
        printf("[%d]\n", cast(int) k);  /* print ASCII code for key */
    }
    printf("\nThe End.\n\n");
}

2004-06-01: Added an untested Linux version based on a suggestion.

 

Intermediate

Using more than one function

DescriptionThis D program shows you how to use more than one function in D.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
/*
    Multiple functions in D
    By B-man
    If you have any comments or questions e-mail me at
    bman_099@yahoo.com
*/

import std.c.stdio;      //Use the standard C library stdio

int main()       //main function
{
    char input_text[26];     //Create an array that will hold the input 
    printf ("Now using the main() function\n");
    printf ("type somthing and press ENTER ");  
    scanf ("%*.s",input_text[25]);   //Scanf function. allows user input.
    function2();  //call the 'function2()' function
    return 0;  //don't return an error
}

function2()  //function2() function
{
    printf ("now using the function2() function\n");
    return 0; //don't return an error
}

/* Originally submitted by bman_099@yahoo.com (Sat Feb 5, 2005 3:15 pm). */ 
 

Character Initial Values

DescriptionTests the initial values for character types.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
void main()
{
    if(char.init == 0)

        printf("DMD 0.92 char.init.\n");
    if(wchar.init == 0)

        printf("DMD 0.92 wchar.init.\n");
    if(dchar.init == 0)

        printf("DMD 0.92 dchar.init.\n");

    if(char.init == 0xFF)
        printf("DMD 0.93+ char.init.\n");
    if(wchar.init == 0xFFFF)
        printf("DMD 0.93+ wchar.init.\n");
    if(wchar.init == 0x0000FFFF)
        printf("DMD 0.93+ dchar.init.\n");
}
 

Module usage

DescriptionSimple decoder and encoder with 8bit and 16bit lookups in separate module with initialization. Also demonstrates associative arrays, foreach. and bit array.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byAnonymous
// There are two separate source code files to be split.
// Test.d -- compile with dmd test.d Lookup.d

/*
 * Encoding:
 * Each word in a text is checked whether it is found in a 256 entry
 * dictionary08 (8 bits) or 512 entry dictionary16 (16 bits). A bit array
 * called "eightCode" is used to indicate which dictionary contained
 * the word. Associative arrays are used for the dictionaries.
 * "codes08" is an array of bytes with the sequence of 'hits' from
 * dictionary08. "codes16" is an array of ushorts with the sequence of
 * 'hits' from dictionary16.
 *
 * Decoding:
 * The "eightCode" bit array is traversed. If true, the corresponding word
 * is pulled from lookup08. If false, the corresponding word is pulled from
 * lookup16. The original "text" is compared with "check" for validation.
 *
 * Caveats:
 * - written by relatively inexperienced D programmer
 * - accomplishes so-so compression with fast decompression
 * 
 * Visual Studio 98 ide project files, exe, and full source available from:
 * http://bibledb.sourceforge.net/misc/ModuleTutorial.zip
 */

import Lookup;

import std.stdio;
import std.string;

const char[][] check  = ["", "", "", "", "", "", "", "", "", ""];
const char[][] text   = ["In", "the", "beginning", "God", "created", 
                         "the", "heavens", "and", "the", "earth."];

ubyte[10]  codes08;
ushort[10] codes16;
bit[10]    eightCode;

void main()
{
  Encode();

  Decode();
}

void Encode()
{
  int  i8 = 0;

  int  i16 = 0;

  foreach (int i, char[] word; text) {
    debug char* w = word;
    if (word in dictionary08) {
      uint code08 = dictionary08[word];
      writef("8:", code08, ' ');
      codes08[i8] = code08;
      i8++;
      eightCode[i] = true;
      continue;
    }
    if (word in dictionary16) {
      uint code16 = dictionary16[word];
      writef("16:", code16, ' ');
      codes16[i16] = code16;
      i16++;
      eightCode[i] = false;
      continue;
    }
    writefln("\nUnmatched word: ", word);
  }
  writefln();
}

void Decode()
{
  int i8 = 0;

  int i16 = 0;


  foreach(int i, bit b; eightCode) {
    char[] curWord;
    if (b == true) {
      curWord = lookup08[codes08[i8]];
      check[i] = curWord;
      writefln(curWord, ' ');
      i8++;
    }
    else {
      curWord = lookup16[codes16[i16]];
      check[i] = curWord;
      writefln(curWord, ' ');
      i16++;
    }
  }
  writefln();
  assert(check == text);
}



// Lookup.d
module Lookup;

static this() {
  foreach (int index, char[] word; lookup08) {
    dictionary08[word] = index;
  }
  foreach (int index, char[] word; lookup16) {
    dictionary16[word] = index;
  }
  dictionary08.rehash;
  dictionary16.rehash;
}
int[char[]] dictionary08;
int[char[]] dictionary16;

char[][] lookup08 = [
"the","and","of","to","in","that","And","he",
"a","I","his","for","shall","is","be","you",
"they","with","will","not","all","your","have","was",
"my","it","from","their","on","are","which","unto",
"them","him","as","were","who","by","said","out",
"but","had","when","this","God","The","up","came",
"into","man","him,","one","there","thy","thou","me",
"said,","come","made","before","no","king","For","has",
"against","son","But","children","put","at","LORD","went",
"we","them,","you,","an","her","ye","Lord","go",
"give","may","make","Then","do","let","people","house",
"He","land","or","so","saying,","men","our","me,",
"even","because","if","upon","Israel","also","every","day",
"after","take","over","these","beginning","great","took","among",
"down","am","did","those","hath","sons","like","she",
"O","gave","us","things","what","So","hand","him.",
"away","Israel,","two","any","sent","then","Jehovah","Now",
"Jesus","whom","Yahweh","given","They","David","brought","them.",
"been","name","say","shalt","word","according","thee","it,",
"you.","know","saw","forth","nor","see","neither","should",
"good","You","evil","its","LORD,","set","through","days",
"Lord,","me.","place","about","now","bring","therefore","If",
"Let","hundred","more","than","would","people,","behold,","heart",
"thee,","Moses","holy","father","way","keep","saith","God.",
"time","done","without","words","own","heard","called","it.",
"When","three","might","where","Behold,","seven","taken","other",
"In","under","It","man,","yet","say,","hast","thousand",
"right","earth","first","This","offering","eat","Judah","house,",
"many","how","again","off","city","himself","whose","cast",
"eyes","back","Israel.","servant","full","Thus","years","voice",
"Yahweh,","Jehovah,","cut","hands","fear","work","turned","cause",
"servants","high","Therefore","says","What","young","until","priest"
];

char[][] lookup16 = [
"created","day,","commanded","send","land,","same","pass","face",
"Judah,","end","glory","thing","together","up,","My","five",
"found","round","death","them;","us,","living","men,","answered",
"speak","As","blood","A","thine","seen","four","toward",
"being","fire","law","son,","hand,","old","very","priests",
"year","side","life","king,","earth,","themselves","sin","Jerusalem,",
"rest","love","soul","Who","cities","another","Jerusalem","Moses,",
"her,","Saul","dwell","There","woman","some","All","both",
"Christ","LORD.","Thou","get","gone","fathers","much","kept",
"chief","Egypt,","hear","become","These","stood","kingdom","him;",
"daughter","between","pass,","became","Son","none","part","only",
"strong","king's","knowledge","having","nations","such","left","burnt",
"ten","flesh","able","them:","mouth","head","tell","near",
"told","certain","That","twenty","little","you;","spake","him:",
"concerning","Why","spoke","midst","till","power","Because","laid",
"We","city,","spirit","turn","David,","you:","faith","bread",
"Aaron","delivered","and,","thus","tribe","altar","mine","while",
"gathered","thereof","deliver","heaven","number","thee.","Solomon","Lord.",
"seed","earth.","mighty","me:","far","drink","thereof,","long",
"me;","water","day.","people.","heart,","peace","Jacob","comes",
"wise","waters","praise","can","Go","things,","pray","father,",
"out,","food","destroy","whole","fell","not,","lay","come,",
"brother","sword","offer","art","seek","lifted","wrath","well",
"heaven,","ark","To","How","six","angel","wife","wicked",
"nothing","spoken","though","mercy","gold","does","covenant","broken",
"fathers,","place,","it;","away,","land.","light","house.","why",
"burned","dead","Of","stand","unclean","Egypt","silver","Take",
"fruit","third","new","don't","save","Spirit","ever.","surely",
"God;","down,","Is","Give","now,","sight","Joshua","gold,",
"inhabitants","offerings","Jerusalem.","written","ear","got","brothers,","bear",
"family","serve","righteousness","second","return","Jews","Israel:","way,",
"princes","walk","didn't","Holy","places","sons,","works","offering,",
"answer","Yahweh.","sea","disciples","judge","going","fall","this,",
"God:","prophet","desire","war","sat","smote","lest","Levites",
"known","us.","lord","Israel;","book","Be","daughters","began",
"Your","body","His","strength","gives","built","righteous","door",
"coming","Jehovah.","Philistines","still","together,","Christ,","open","hold",
"ever","multitude","begat","Father","you?","days,","call","above",
"within","gate","Joseph","thirty","hand.","reigned","waste","men.",
"cry","priest,","forty","Jesus,","yourselves","twelve","false","eyes,",
"sea,","feet","passed","it:","child","there,","servant,","death.",
"receive","find","servants,","wisdom","name,","time,","ready","poor",
"place.","field","death,","night","Pharaoh","tabernacle","sword,","again,",
"mother","mount","brothers","month,","prophets","border","One","sacrifice",
"show","could","not.","never","joy","knew","clear","Abraham",
"whether","witness","build","blessed","cried","I,","makes","throughout",
"vessels","children,","carried","wine","Do","wife,","enter","returned",
"law,","cubits","middle","goes","life,","By","stone","destruction",
"grace","manner","fifty","ears","received","fire,","worship","dead,",
"Ye","women","help","anger","orders","nations,","me?","seventh",
"inheritance","filled","also,","elders","voice,","captain","LORD:","gather",
"asked","father's","saying","prayer","that,","world","town","kill",
"ways","offered","cannot","oil","valley","slew","most","hope",
"congregation","here","better","priests,",
"himself,","commandment","sought","silver,",
"Peter","LORD;","brethren,","Babylon,","true","must","sheep","gods",
"Jeremiah","looking","half","rose","man's","east","covered","Jacob,",
"meat","fat","burn","another,","male","side,","country","captains",
"look","there.","away.","named","departed","Babylon","shut","break",
"numbered","meet","king.","judgment","Have","brother,","water,","money",
"times","Samuel","King","burning","morning","heads","feast","army",
"thee;","seeing","lie","her.","families","month","Paul","therefore,",
"iniquity","houses","Even","Moreover","Egypt.","She","Aaron,","wilderness",
"wall","in,","fine","answered,","flesh,","words,","die","making",
"born","sins","night,","wherein","live","appointed","sound","heavens"
];
 

Asm code for splitting ubyte into low and high nibbles

DescriptionDemonstrates using asm code with local variables
Date/TimeSat Nov 5, 2005 12:00 am
Posted byAnonymous
/*
 *  Copyright (C) 2004 by Digital Mars, www.digitalmars.com
 *  Written by Lynn Allan
 *  This software is provided 'as-is' by a rusty asm-486 programmer.
 *  Released to public domain.
 *
 * Compile with: dmd test.d (uses dmd ver 0.102)
 */

import std.stdio;

void main ()
{
  ubyte x = 0x12;
  ubyte y = 0x9a;
  ubyte xLoNibble = (x & 0x0F);
  ubyte xHiNibble = (x >> 4);
  ubyte yLoNibble = (y & 0x0F);
  ubyte yHiNibble = (y >> 4);
  writefln("x: ", x, "  xLoNibble: ", xLoNibble, "  xHiNibble: ", xHiNibble);
  writefln("y: ", y, "  yLoNibble: ", yLoNibble, "  yHiNibble: ", yHiNibble);

  asm
  {
    movzx  BX,x;
    mov    AX,BX;
    and    BX,15;
    mov    xLoNibble,BL;
    shr    AX,4;
    mov    xHiNibble,AL;

    movzx  BX,y;
    mov    AX,BX;
    and    BX,15;
    mov    yLoNibble,BL;
    shr    AX,4;
    mov    yHiNibble,AL;
  }
  assert(xLoNibble == 2);
  assert(xHiNibble == 1);
  assert(yLoNibble == 10);
  assert(yHiNibble == 9);
  writefln("x: ", x, "  xLoNibble: ", xLoNibble, "  xHiNibble: ", xHiNibble);
  writefln("y: ", y, "  yLoNibble: ", yLoNibble, "  yHiNibble: ", yHiNibble);
}
 

Asm code for finding first occurrence of letter in string

DescriptionMore or less equivalent to std.string.find. (also similar to C-RTL for strchr except finds count offset rather than char*). Demonstrates reference of local char[] variable, repne, scasb, etc.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byAnonymous
/*
 *  Copyright (C) 2004 by Digital Mars, www.digitalmars.com
 *  Written by Lynn Allan
 *  This software is provided 'as-is' by a rusty asm-486 programmer.
 *  Released to public domain.
 *
 * Compile with: dmd test.d (uses dmd ver 0.102)
 */

import std.stdio;
import std.string;

void main ()
{
  char[] searchString = "The quick brown fox jumped over the lazy dog.";
  //                     00000000001111111111222222222233333333334444
  //                     01234567890123456789012345678901234567890123
  char* pss = &searchString[0];
  uint foundOffset = find(searchString, 'z');
  uint zCode = 'z';
  uint len = searchString.length;
  writefln("z found at: ", foundOffset);
  uint xCode = 'x';
  foundOffset = find(searchString, 'x');
  len = searchString.length;
  writefln("x found at: ", foundOffset);

  asm {
    cld;
    mov   ECX,len;
    mov   EAX,zCode;
    mov   EDI,pss;
    repne;
    scasb;
    mov   EBX,len;
    sub   EBX,ECX;
    dec   EBX;
    mov   foundOffset,EBX;
  }
  writefln("z found at: ", foundOffset);
  assert(foundOffset==38);

  asm {
    cld;
    mov   ECX,len;
    mov   EAX,xCode;
    mov   EDI,pss;
    repne;
    scasb;
    mov   EBX,len;
    sub   EBX,ECX;
    dec   EBX;
    mov   foundOffset,EBX;
  }
  writefln("x found at: ", foundOffset);
  assert(foundOffset==18);
}
 

Towers of Hanoi

DescriptionSolves the Hanoi problem for seven discs.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byAnonymous
/+
 + hanoi!
 + solves the hanoi problem for seven discs
 +
 + by Brian Waters
 +/

import std.c.stdio;

int main(char[][] args)
{
    void solve(int from, int aux, int to, int numdiscs)
    {
        if (numdiscs == 0)

            return;
        solve(from, to, aux, numdiscs - 1);
        printf("%i to %i\n", from, to);
        solve(aux, from, to, numdiscs - 1);
        return;
    }
    
    solve(1, 2, 3, 7);
    
    return 0;

}
 

Factorial

DescriptionShows how a factorial function can be written using a for loop.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
uint factorial(int a)
{

    /*
        A factorial is a mathematical concept that is typically denoted with a "!".

        Example:
        4! = 4 * 3 * 2 * 1 = 24
    */


    if(a == 0) return 1;

    uint b = 1;
    for(int i = 1; i <= a; i++)
        b *= i;
    return b;
}

import std.c.stdio;

unittest
{

    /* Compile with the "-unittest" option to run these unittests. */

    printf("Attempting unittests...\n");
    assert(factorial(0) == 1);
    assert(factorial(1) == 1);
    assert(factorial(2) == 2);
    assert(factorial(3) == 6);
    assert(factorial(4) == 24);
    printf("unittests successful...\n");
}

void main()
{
    printf("factorial(0): %d\n", factorial(0));
    printf("factorial(1): %d\n", factorial(1));
    printf("factorial(2): %d\n", factorial(2));
    printf("factorial(3): %d\n", factorial(3));
    printf("factorial(4): %d\n", factorial(4));
}
 

Escape Sequences

DescriptionEscape sequence are useful, but they can get tricky.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
/*

File:    escape.d
Author:  J C Calvarese
Website: http://jcc_7.tripod.com/d/
License: Public Domain

Purpose: 
Demonstrates how to use escaping to put backslashes and apostrophes 
for a literal character.

*/

const char[] backslashWYSIWYG = `\`;
const char[] quoteWYSIWYG = `'`;
const char[] doubleQuoteWYSIWYG = `"`;

const char[] doubleQuoteReg = "\"";
const char[] quoteReg = "\'";
const char[] backslahReg = "\\";


const char quoteChar = '\'';

const char backslashChar = '\\';



void main()
{
    printf(cast(char[]) (doubleQuoteReg ~ "That's what I said!" ~ doubleQuoteReg ~ \n\0));  
}
 

Comments (Reprise)

DescriptionMore comments is better than fewer comments.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
module comments;

/* This purpose of this code is to 
   show how documentation can be done with comments. */


/*/   */


// single line


import std.string;

/*

Mult-line

*/

int usefulInteger;

/+ 

simple nested

+/

char[] someString;

/+ 
/+/ +/
level 1 nested

    /+
    
    level 2 nested
    
        /+
        level 3 nested
        +/
    
    +/

+/


/* The actual program (anti-climatic) */

int main()
{
    char[] someOtherString = someString;
    
    int anotherInt = usefulInteger;
    
    return 0;


}
 

Nested Comments

DescriptionThis program doesn't do anything, but it's well-documented.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
/* 

nested_comments.html 

Author: J C Calvarese
License: public domain

This program demonstrates using comments in D.

(Such as the multi-line comment this sentence resides in.)

*/



/+   

    This is one of D's nested comments.  


    /+ What would an example of a nested comment be without 
       a nested (and /+ another nest +/ )comment? +/

    /* Naturally, you can also put something like this in a nested multiline comments... */

    // as well as text like like this ...

    /* since the compiler is only concerned about being in a nested comment block,
        you don't actually need a matching * and / to satisfy the compiler.

+/



void main()  
{ // This is a single line comment.  It automatically ends at the end of the line.
}
 

String Literals

DescriptionShows how different types of string literals work.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
/* "Backquote" WYSIWYG strings */

const char[] a1 = `\`;
const char[] b1 = `\\`;
const char[] c1 = `\"`;



/* r"" WYSIWYG strings */

const char[] a2 = r"\";
const char[] b2 = r"\\";
const char[] c2 = r"\" `"`; 
/* The r"" strings can't contain a ", so I used concatenation. */



/* "Regular strings */

const char[] a3 = "\\";
const char[] b3 = "\\\\";
const char[] c3 = "\\\"";



void main()
{
    printf("Test that the strings mean what I think they mean.\n");

    assert(a1 == a2);
    assert(a1 == a3);

    assert(b1 == b2);
    assert(b1 == b3);

    assert(c1 == c2);
    assert(c1 == c3);

    printf("Tests passed!\n");

}
 

String and Number Literals

DescriptionWhen DMD 0.69 was released, I came up with this example to try it out.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
/* 

File:      d069.d
Author:    Justin C. Calvarese
Website:   http://jcc_7.tripod.com/d/
License:   Public Domain

Purpose:
Since D 0.69, integer and floating point literals
can have embedded underscores (_) for formatting purposes.

This code demonstrates those features and more...

*/

const int hundred = 100;
const int million = 1_000_000;



/*

Also added in 0.69...

x"0a AA BF" style hex strings.

*/

const char[] myName = x"4A 75 73 74 69 6E"; 


const char[] notRaw = "string\tstring";


/*

Raw (what-you-see-is-what-you-get) strings
implemented in D 0.69

*/

const char[] raw1 = r"string\tstring";
const char[] raw2 = `string\tstring`;
const char[] raw3 = `apostrophe: '  fancy quote: ` ~ "`";



/* See how the strings are automatically concatenated... */
const char[] oneToFive = "one" \t "two" \t "three" \t "four" \t  \t "five";

/* Binary Notation: I'm saying "two" */
const int binTwo      = 0b10;
const int binFancyTwo = 0b000_0010;

/* Hexadecimal Notation: I'm saying "16" */
const int hexSixteen      = 0x10;
const int hexFancySixteen = 0x00_10;

/* Hexadecimal Notation: I'm saying "8" */
const int octEight = 010;


int main() 
{

    /* Print "1000000" */
    printf("%i\n", million);    

    /* Print "2" */
    printf("%i\n", binTwo);  

    /* Print "16" */
    printf("%i\n", hexSixteen);  

    /* Print "8" */
    printf("%i\n", octEight);  


    /* Print "Justin" */
    printf("%.*s\n", myName);   

    /* Print a string with backslashed characters */
    printf("\"Invisible\" backslashed characters: %.*s\n", notRaw); 

    /* Prints a what-you-see-is-what-you-get string */
    printf("What-you-see-is-what-you-get [1]: %.*s\n", raw1);   

    /* Prints a what-you-see-is-what-you-get string */
    printf("What-you-see-is-what-you-get [2]: %.*s\n", raw2);   

    /* Prints a what-you-see-is-what-you-get string */
    printf("What-you-see-is-what-you-get [3]: %.*s\n", raw3);   

    /* Prints one to five */
    printf("one-to-five: %.*s\n\n", oneToFive);


    printf("This is the first line.
This is the second line.
I'd say that D is pretty darn cool (third line).

");


    return 0;


}
 

Runtime Type Information (RTTI)

DescriptionYou can find out some class information during runtime.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
import std.c.stdio;

class A {}

int main ( char [] [] args ) 
{
    A a = new A;
    Object o;
    o = new Object;
    bit b;
    
    printf("%.*s\n", a.classinfo.name);
    printf("%.*s\n", o.classinfo.name);

    /* These aren't allowed... */
//    printf("%.*s\n", b.classinfo.name);
//    printf("%.*s\n", b.typeinfo.name);

    return 1;
}

/* 

See also: 
http://www.prowiki.org/wiki4d/wiki.cgi?HowTo/RealtimeTypeInformation
http://www.prowiki.org/wiki4d/wiki.cgi?FaqRoadmap#DoesDsupportanyformofRTTI

*/ 
 

Statistics

DescriptionDemonstrates calculating linear regression statistics.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byjcc7
/*

File:      stat.d
Author:    Justin C. Calvarese
Website:   http://jcc_7.tripod.com/d/
License:   Public Domain

Linear regression statistics.

*/



double average(double[] r)
{
    double t = 0;



    for(int i=0; i < r.length; i++)
     t += r[i];

    return (t / (cast(double) r.length));
}


double beta1(double[] x, double[] y, double x_bar, double y_bar)
{
    int l;

    if (x.length != y.length) 
    {
        printf("x and y really should be the same length!");

        // Set length as the shorter series and move on...

        if(x.length < y.length) l = x.length;
        else l = y.length;
    }
    else l = x.length;


    double top_sum, btm_sum;

    top_sum = 0;


    for(int i = 0; i < l; i++)
     top_sum += (x[i] - x_bar) * (y[i] - y_bar);


    btm_sum = 0;


    for(int i = 0; i < l; i++)
     btm_sum += ((x[i] - x_bar) * (x[i] - x_bar));


    return top_sum / btm_sum;
}




double beta0(double x_bar, double y_bar, double b1)
{
    return y_bar - (b1 * x_bar);
}





int main()
{

    double[] x;

    x.length = 10;

    x[0] = 1;
    x[1] = 2;
    x[2] = 3;
    x[3] = 4;
    x[4] = 5;
    x[5] = 6.5;
    x[6] = 7;
    x[7] = 7.5;
    x[8] = 8;
    x[9] = 8.5 ;


    double[] y;

    y.length = 10;

    y[0] = 1;
    y[1] = 2;
    y[2] = 3;
    y[3] = 3.2;
    y[4] = 3.4;
    y[5] = 4;
    y[6] = 4.2;
    y[7] = 4.3;
    y[8] = 4.35;
    y[9] = 4.37;


    double x_bar, y_bar;

    x_bar = average(x);
    y_bar = average(y);


    double b1, b0;
    b1 = beta1(x, y, x_bar, y_bar);    
    b0 = beta0(x_bar, y_bar, b1);    

    printf("b1: %f\n", b1);
    printf("b0: %f\n", b0);


    return 0;


}
 

Advanced

Printing international characters on Windows

DescriptionThis Windows specific code, allows you to print international characters (Greek for instance) on the non UTF-8 Windows console.
Date/TimeSat Nov 5, 2005 12:00 am
Posted byAnonymous
// Posted by psychotic
// Based on http://www.digitalmars.com/d/archives/digitalmars/D/12787.html
// Link to kernel32.lib

import std.c.stdio;
import std.c.windows.windows;

extern (Windows) {
    export BOOL CharToOemW(
            LPCWSTR lpszSrc, // string to translate
            LPSTR lpszDst // translated string
    );
}

void main()
{
    wchar[] s = "Χαίρετε!"; //Greek salutation
    echo(s); // call our function
}

void echo(wchar[] s)
{
    char[] t = new char[s.length];
    CharToOemW(s, t); // calling Windows API function
    puts(t); // printing translated string
}