Bahasa pengaturcaraan D

Daripada Wikipedia, ensiklopedia bebas.
Lompat ke: pandu arah, cari
D
Paradigma berbilang paradigma
Muncul pada 1999
Direka oleh Walter Bright
Lepasan stabil 1.016 (stabil) (Jun 17 2007)
Disiplin penjenisan kuat, statik
Pelaksanaan utama DMD, GDC
Dipengaruhi C, C++, C#, Java, Eiffel

D merupakan bahasa pengaturcaraan sistem pelbagai-paradigm imperatif berorentasi objek oleh Walter Bright dari Digital Mars. Ia asalnya (re-engineering) C++, tetapi sungguhpun ia banyak dipengaruhi oleh bahasa tersebut, ia bukannya variasi C++. D telah mereka semula ciri-ciri C++ dan dipengaruhi oleh konsep yang digunakan dalam bahasa lain, seperti Java, C# dan Eiffel. Versi 1.0 yang stabil dibebaskan pada 2 Januari 2007. Versi ujian, 2.000, dibebaskan pada 17 Jun 2007.


Contoh[sunting | sunting sumber]

Kata kekunci diwarnakan biru, rentetan pula merah, manakala ulasan diwarnakan hijau.

Contoh 1[sunting | sunting sumber]

Atur cara contoh berikut memaparkan argumen-argumen baris perintahnya. Fungsi main ialah titik masuk bagi atur cara D, dan args ialah tatasusunan rentetan mewakili argumen-argumen baris perintah. Rentetan dalam D ialah sebuah tatasusunan aksara yang diwakili oleh char[].

import std.stdio;       // for writefln()
int main(char[][] args)
{
    foreach(i, a; args)
        writefln("args[%d] = '%s'", i, a);
    return 0;
}

Kenyataan foreach boleh mengulang apa jua koleksi, di sini ia menghasilkan tatasusunan indeks (i) dan nilai (a) daripada tatasusunan args. Jenis bagi indeks i dan nilai a diketahui melalui jeni bagi tatasusunan args.

Contoh 2[sunting | sunting sumber]

This illustrates the use of associative arrays to build much more complex data structures.

import std.stdio;       // for writefln()

int main(char[][] args)
{
    // Declare an associative array with string keys and
    // arrays of strings as data
    char[][] [char[]] container;

    // Add some people to the container and let them carry some items
    container["Anya"] ~= "scarf";
    container["Dimitri"] ~= "tickets";
    container["Anya"] ~= "puppy";

    // Iterate over all the persons in the container
    foreach (char[] person, char[][] items; container)
        display_item_count(person, items);
    return 0;
}

void display_item_count(char[] person, char[][] items)
{
    writefln(person, " is carrying ", items.length, " items.");
}

Contoh 3[sunting | sunting sumber]

This heavily annotated example highlights many of the differences from C++, while still retaining some C++ aspects.

#!/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
 * or to get generated documentation:
 *   dmd hello.d -D
 */

import std.stdio;                        // References to  commonly used I/O routines.

int main(char[][] args)                 
{
    // 'writefln' (Write-Formatted-Line) is the type-safe 'printf'
    writefln("Hello World, "             // automatic concatenation of string literals
             "Reloaded");

    // Strings are denoted as a dynamic array of chars 'char[]'
    // auto type inference and built-in foreach
    foreach(argc, argv; args)
    {
        auto cl = new CmdLin(argc, argv);                        // OOP is supported
        writefln(cl.argnum, cl.suffix, " arg: %s", cl.argv);        // user-defined class properties.

        delete cl;                    // Garbage Collection or explicit memory management - your choice
    }

    // Nested structs, classes and functions
    struct specs
    {
        // all vars automatically initialized to 0 at runtime
        int count, allocated;
        // however you can choose to avoid array initialization
        int[10000] bigarray = void;
    }

    specs argspecs(char[][] args)
    // Optional (built-in) function contracts.
    in
    {
        assert(args.length > 0);                   // assert built in
    }
    out(result)
    {
        assert(result.count == CmdLin.total);
        assert(result.allocated > 0);
    }
    body
    {
        specs* s = new specs;
        // no need for '->'
        s.count = args.length;  // The 'length' property is number of elements.
        s.allocated = typeof(args).sizeof; // built-in properties for native types
        foreach(arg; args)
            s.allocated += arg.length * typeof(arg[0]).sizeof;
        return *s;
    }

    // built-in string and common string operations, eg. '~' is concatenate.
    char[] argcmsg  = "argc = %d";
    char[] allocmsg = "allocated = %d";
    writefln(argcmsg ~ ", " ~ allocmsg,
            argspecs(args).count,argspecs(args).allocated);
    return 0;
}

/**
 * Stores a single command line argument.
 */
class CmdLin
{
    private
    {
        int _argc;
        char[] _argv;
        static uint _totalc;
    }

    public:
        /**
         * Object constructor.
         * params:
         *   argc = ordinal count of this argument.
         *   argv = text of the parameter
         */
        this(int argc, char[] argv)
        {
            _argc = argc + 1;
            _argv = argv;
            _totalc++;
        }

        ~this() // Object destructor
        {
            // Doesn't actually do anything for this example.
        }

        int argnum() // A property that returns arg number
        {
            return _argc;
        }

        char[] argv() // A property that returns arg text
        {
            return _argv;
        }

        wchar[] suffix() // A property that returns ordinal suffix
        {
            wchar[] suffix; // Built in Unicode strings (UTF-8, UTF-16, UTF-32)
            switch(_argc)
            {
                case 1:
                    suffix = "st";
                    break;
                case 2:
                    suffix = "nd";
                    break;
                case 3:
                    suffix = "rd";
                    break;
                default:  // 'default' is mandatory with "-w" compile switch.
                    suffix = "th";
            }
            return suffix;
        }

        /**
         * A static property, as in C++ or Java,
         * applying to the class object rather than instances.
         * returns: The total number of commandline args added.
         */
        static typeof(_totalc) total()
        {
            return _totalc;
        }

        // Class invariant, things that must be true after any method is run.
        invariant
        {
            assert(_argc > 0);
            assert(_totalc >= _argc);
        }
}


Pautan luar[sunting | sunting sumber]

Wikibuku
Wikibuku mempunyai satu buku topik mengenai


Bahasa pengaturcaraan (senarai penuh, perbandingan, glosari)
ALGOL | APL | Ada | BASIC| C | C++ | C# | COBOL | Common Lisp | Eiffel | FORTH | Fortran | Haskell | Java | JavaScript | Jython | LISP | LOGO | Mesa | Modula-2 | Oberon | OCaml | Objective-C | Perl | PHP | Prolog | PL/I | Pascal | PostScript | Python | Ruby | Scheme | Smalltalk | SQL | Tcl | Visual Basic