Bahasa pengaturcaraan D

From Wikipedia, the free encyclopedia

Bahasa pengaturcaraan D
Remove ads

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.

Fakta Segera Paradigma, Muncul pada ...
Remove ads

Contoh

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

Contoh 1

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

Berikut menunjukkan penggunaan tatasusunan bersekutu bagi membentuk struktur data yang lebih kompleks

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

Contoh yang mempunyai banyak anotasi berikut menonjolkan banyak perbezaan berbanding C++, sambil masih mengekalkan beberapa aspek C++.

#!/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);
	}
}
Remove ads

Pautan luar

Remove ads

Rujukan

Loading related searches...

Wikiwand - on

Seamless Wikipedia browsing. On steroids.

Remove ads