D Programming – Useful Resources ”; Previous Next The following resources contain additional information on D Programming. Please use them to get more in-depth knowledge on this topic. Useful Video Courses 2D and 3D Animation with After Effects 14 Lectures 1 hours Harshit Srivastava More Detail WebGL 2D/3D Programming and Graphics Rendering For The Web 29 Lectures 4 hours Frahaan Hussain More Detail Create a 3D multi-player game using THREE.js and Socket.IO 35 Lectures 2.5 hours Nicholas Lever More Detail Java Courses in Tamil 188 Lectures 11.5 hours Programming Line More Detail 3D Modeling in Blender 2.8 for Unity Video Game Developers 59 Lectures 7 hours Billy McDaniel More Detail Création d”un tableau de bord de suivi d”activité avec Excel 18 Lectures 2 hours Marc Augier More Detail Print Page Previous Next Advertisements ”;
Category: d Programming
D Programming – Aliases
D Programming – Aliases ”; Previous Next Alias, as the name refers provides an alternate name for existing names. The syntax for alias is shown below. alias new_name = existing_name; The following is the older syntax, just in case you refer some older format examples. Its is strongly discouraged the use of this. alias existing_name new_name; There is also another syntax that is used with expression and it is given below in which we can directly use the alias name instead of the expression. alias expression alias_name ; As you may know, a typedef adds the ability to create new types. Alias can do the work of a typedef and even more. A simple example for using alias is shown below that uses the std.conv header which provides the type conversion ability. Live Demo import std.stdio; import std.conv:to; alias to!(string) toString; void main() { int a = 10; string s = “Test”~toString(a); writeln(s); } When the above code is compiled and executed, it produces the following result − Test10 In the above example instead of using to!string(a), we assigned it to alias name toString making it more convenient and simpler to understand. Alias for a Tuple Let us a look at another example where we can set alias name for a Tuple. Live Demo import std.stdio; import std.typetuple; alias TypeTuple!(int, long) TL; void method1(TL tl) { writeln(tl[0],”t”, tl[1] ); } void main() { method1(5, 6L); } When the above code is compiled and executed, it produces the following result − 5 6 In the above example, the type tuple is assigned to the alias variable and it simplifies the method definition and access of variables. This kind of access is even more useful when we try to reuse such type tuples. Alias for Data Types Many times, we may define common data types that needs to be used across the application. When multiple programmers code an application, it can be cases where one person uses int, another double, and so on. To avoid such conflicts, we often use types for data types. A simple example is shown below. Example Live Demo import std.stdio; alias int myAppNumber; alias string myAppString; void main() { myAppNumber i = 10; myAppString s = “TestString”; writeln(i,s); } When the above code is compiled and executed, it produces the following result − 10TestString Alias for Class Variables There is often a requirement where we need to access the member variables of the superclass in the subclass, this can made possible with alias, possibly under a different name. In case you are new to the the concept of classes and inheritance, have a look at the tutorial on classes and inheritance before starting with this section. Example A simple example is shown below. Live Demo import std.stdio; class Shape { int area; } class Square : Shape { string name() const @property { return “Square”; } alias Shape.area squareArea; } void main() { auto square = new Square; square.squareArea = 42; writeln(square.name); writeln(square.squareArea); } When the above code is compiled and executed, it produces the following result − Square 42 Alias This Alias this provides the capability of automatic type conversions of user-defined types. The syntax is shown below where the keywords alias and this are written on either sides of the member variable or member function. alias member_variable_or_member_function this; Example An example is shown below to show the power of alias this. Live Demo import std.stdio; struct Rectangle { long length; long breadth; double value() const @property { return cast(double) length * breadth; } alias value this; } double volume(double rectangle, double height) { return rectangle * height; } void main() { auto rectangle = Rectangle(2, 3); writeln(volume(rectangle, 5)); } In the above example, you can see that the struct rectangle is converted to double value with the help of alias this method. When the above code is compiled and executed, it produces the following result − 30 Print Page Previous Next Advertisements ”;
D Programming – Mixins
D Programming – Mixins ”; Previous Next Mixins are structs that allow mixing of the generated code into the source code. Mixins can be of the following types − String Mixins Template Mixins Mixin name spaces String Mixins D has the capability to insert code as string as long as that string is known at compile time. The syntax of string mixins is shown below − mixin (compile_time_generated_string) Example A simple example for string mixins is shown below. Live Demo import std.stdio; void main() { mixin(`writeln(“Hello World!”);`); } When the above code is compiled and executed, it produces the following result − Hello World! Here is another example where we can pass the string in compile time so that mixins can use the functions to reuse code. It is shown below. Live Demo import std.stdio; string print(string s) { return `writeln(“` ~ s ~ `”);`; } void main() { mixin (print(“str1”)); mixin (print(“str2”)); } When the above code is compiled and executed, it produces the following result − str1 str2 Template Mixins D templates define common code patterns, for the compiler to generate actual instances from that pattern. The templates can generate functions, structs, unions, classes, interfaces, and any other legal D code. The syntax of template mixins is as shown below. mixin a_template!(template_parameters) A simple example for string mixins is shown below where we create a template with class Department and a mixin instantiating a template and hence making the the functions setName and printNames available to the structure college. Example Live Demo import std.stdio; template Department(T, size_t count) { T[count] names; void setName(size_t index, T name) { names[index] = name; } void printNames() { writeln(“The names”); foreach (i, name; names) { writeln(i,” : “, name); } } } struct College { mixin Department!(string, 2); } void main() { auto college = College(); college.setName(0, “name1”); college.setName(1, “name2”); college.printNames(); } When the above code is compiled and executed, it produces the following result − The names 0 : name1 1 : name2 Mixin Name Spaces Mixin name spaces are used to avoid ambiguities in template mixins. For example, there can be two variables, one defined explicitly in main and the other is mixed in. When a mixed-in name is the same as a name that is in the surrounding scope, then the name that is in the surrounding scope gets used. This example is shown below. Example Live Demo import std.stdio; template Person() { string name; void print() { writeln(name); } } void main() { string name; mixin Person a; name = “name 1”; writeln(name); a.name = “name 2″; print(); } When the above code is compiled and executed, it produces the following result − name 1 name 2 Print Page Previous Next Advertisements ”;
D Programming – Contract
D – Contract Programming ”; Previous Next Contract programming in D programming is focused on providing a simple and understandable means of error handling. Contract programming in D are implemented by three types of code blocks − body block in block out block Body Block in D Body block contains the actual functionality code of execution. The in and out blocks are optional while the body block is mandatory. A simple syntax is shown below. return_type function_name(function_params) in { // in block } out (result) { // in block } body { // actual function block } In Block for Pre Conditions in D In block is for simple pre conditions that verify whether the input parameters are acceptable and in range that can be handled by the code. A benefit of an in block is that all of the entry conditions can be kept together and separate from the actual body of the function. A simple precondition for validating password for its minimum length is shown below. Live Demo import std.stdio; import std.string; bool isValid(string password) in { assert(password.length>=5); } body { // other conditions return true; } void main() { writeln(isValid(“password”)); } When the above code is compiled and executed, it reads the file created in previous section and produces the following result − true Out Blocks for Post Conditions in D The out block takes care of the return values from the function. It validates the return value is in expected range. A simple example containing both in and out is shown below that converts months, year to a combined decimal age form. Live Demo import std.stdio; import std.string; double getAge(double months,double years) in { assert(months >= 0); assert(months <= 12); } out (result) { assert(result>=years); } body { return years + months/12; } void main () { writeln(getAge(10,12)); } When the above code is compiled and executed, it reads the file created in previous section and produces the following result − 12.8333 Print Page Previous Next Advertisements ”;
D Programming – Overloading
D Programming – Overloading ”; Previous Next D allows you to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloading respectively. An overloaded declaration is a declaration that had been declared with the same name as a previous declaration in the same scope, except that both declarations have different arguments and obviously different definition (implementation). When you call an overloaded function or operator, the compiler determines the most appropriate definition to use by comparing the argument types you used to call the function or operator with the parameter types specified in the definitions. The process of selecting the most appropriate overloaded function or operator is called overload resolution.. Function Overloading You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type. Example The following example uses same function print() to print different data types − Live Demo import std.stdio; import std.string; class printData { public: void print(int i) { writeln(“Printing int: “,i); } void print(double f) { writeln(“Printing float: “,f ); } void print(string s) { writeln(“Printing string: “,s); } }; void main() { printData pd = new printData(); // Call print to print integer pd.print(5); // Call print to print float pd.print(500.263); // Call print to print character pd.print(“Hello D”); } When the above code is compiled and executed, it produces the following result − Printing int: 5 Printing float: 500.263 Printing string: Hello D Operator Overloading You can redefine or overload most of the built-in operators available in D. Thus a programmer can use operators with user-defined types as well. Operators can be overloaded using string op followed by Add, Sub, and so on based on the operator that is being overloaded. We can overload the operator + to add two boxes as shown below. Box opAdd(Box b) { Box box = new Box(); box.length = this.length + b.length; box.breadth = this.breadth + b.breadth; box.height = this.height + b.height; return box; } The following example shows the concept of operator overloading using a member function. Here an object is passed as an argument whose properties are accessed using this object. The object which calls this operator can be accessed using this operator as explained below − Live Demo import std.stdio; class Box { public: double getVolume() { return length * breadth * height; } void setLength( double len ) { length = len; } void setBreadth( double bre ) { breadth = bre; } void setHeight( double hei ) { height = hei; } Box opAdd(Box b) { Box box = new Box(); box.length = this.length + b.length; box.breadth = this.breadth + b.breadth; box.height = this.height + b.height; return box; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; // Main function for the program void main( ) { Box box1 = new Box(); // Declare box1 of type Box Box box2 = new Box(); // Declare box2 of type Box Box box3 = new Box(); // Declare box3 of type Box double volume = 0.0; // Store the volume of a box here // box 1 specification box1.setLength(6.0); box1.setBreadth(7.0); box1.setHeight(5.0); // box 2 specification box2.setLength(12.0); box2.setBreadth(13.0); box2.setHeight(10.0); // volume of box 1 volume = box1.getVolume(); writeln(“Volume of Box1 : “, volume); // volume of box 2 volume = box2.getVolume(); writeln(“Volume of Box2 : “, volume); // Add two object as follows: box3 = box1 + box2; // volume of box 3 volume = box3.getVolume(); writeln(“Volume of Box3 : “, volume); } When the above code is compiled and executed, it produces the following result − Volume of Box1 : 210 Volume of Box2 : 1560 Volume of Box3 : 5400 Operator Overloading Types Basically, there are three types of operator overloading as listed below. Sr.No. Overloading Types 1 Unary Operators Overloading 2 Binary Operators Overloading 3 Comparison Operators Overloading Print Page Previous Next Advertisements ”;
D Programming – Exception Handling ”; Previous Next An exception is a problem that arises during the execution of a program. A D exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another. D exception handling is built upon three keywords try, catch, and throw. throw − A program throws an exception when a problem shows up. This is done using a throw keyword. catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception. try − A try block identifies a block of code for which particular exceptions are activated. It is followed by one or more catch blocks. Assuming a block will raise an exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following − try { // protected code } catch( ExceptionName e1 ) { // catch block } catch( ExceptionName e2 ) { // catch block } catch( ExceptionName eN ) { // catch block } You can list down multiple catch statements to catch different type of exceptions in case your try block raises more than one exception in different situations. Throwing Exceptions in D Exceptions can be thrown anywhere within a code block using throw statements. The operand of the throw statements determines a type for the exception and can be any expression and the type of the result of the expression determines the type of exception thrown. The following example throws an exception when dividing by zero condition occurs − Example double division(int a, int b) { if( b == 0 ) { throw new Exception(“Division by zero condition!”); } return (a/b); } Catching Exceptions in D The catch block following the try block catches any exception. You can specify what type of exception you want to catch and this is determined by the exception declaration that appears in parentheses following the keyword catch. try { // protected code } catch( ExceptionName e ) { // code to handle ExceptionName exception } The above code catches an exception of ExceptionName type. If you want to specify that a catch block should handle any type of exception that is thrown in a try block, you must put an ellipsis,…, between the parentheses enclosing the exception declaration as follows − try { // protected code } catch(…) { // code to handle any exception } The following example throws a division by zero exception. It is caught in catch block. Live Demo import std.stdio; import std.string; string division(int a, int b) { string result = “”; try { if( b == 0 ) { throw new Exception(“Cannot divide by zero!”); } else { result = format(“%s”,a/b); } } catch (Exception e) { result = e.msg; } return result; } void main () { int x = 50; int y = 0; writeln(division(x, y)); y = 10; writeln(division(x, y)); } When the above code is compiled and executed, it reads the file created in previous section and produces the following result − Cannot divide by zero! 5 Print Page Previous Next Advertisements ”;
D Programming – Abstract Classes ”; Previous Next Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one that cannot be instantiated. All other functionality of the class still exists, and its fields, methods, and constructors are all accessed in the same manner. You just cannot create an instance of the abstract class. If a class is abstract and cannot be instantiated, the class does not have much use unless it is subclass. This is typically how abstract classes come about during the design phase. A parent class contains the common functionality of a collection of child classes, but the parent class itself is too abstract to be used on its own. Using Abstract Class in D Use the abstract keyword to declare a class abstract. The keyword appears in the class declaration somewhere before the class keyword. The following shows an example of how abstract class can be inherited and used. Example Live Demo import std.stdio; import std.string; import std.datetime; abstract class Person { int birthYear, birthDay, birthMonth; string name; int getAge() { SysTime sysTime = Clock.currTime(); return sysTime.year – birthYear; } } class Employee : Person { int empID; } void main() { Employee emp = new Employee(); emp.empID = 101; emp.birthYear = 1980; emp.birthDay = 10; emp.birthMonth = 10; emp.name = “Emp1”; writeln(emp.name); writeln(emp.getAge); } When we compile and run the above program, we will get the following output. Emp1 37 Abstract Functions Similar to functions, classes can also be abstract. The implementation of such function is not given in its class but should be provided in the class that inherits the class with abstract function. The above example is updated with abstract function. Example Live Demo import std.stdio; import std.string; import std.datetime; abstract class Person { int birthYear, birthDay, birthMonth; string name; int getAge() { SysTime sysTime = Clock.currTime(); return sysTime.year – birthYear; } abstract void print(); } class Employee : Person { int empID; override void print() { writeln(“The employee details are as follows:”); writeln(“Emp ID: “, this.empID); writeln(“Emp Name: “, this.name); writeln(“Age: “,this.getAge); } } void main() { Employee emp = new Employee(); emp.empID = 101; emp.birthYear = 1980; emp.birthDay = 10; emp.birthMonth = 10; emp.name = “Emp1″; emp.print(); } When we compile and run the above program, we will get the following output. The employee details are as follows: Emp ID: 101 Emp Name: Emp1 Age: 37 Print Page Previous Next Advertisements ”;
D Programming – File I/O
D Programming – File I/O ”; Previous Next Files are represented by the File struct of the std.stdio module. A file represents a sequence of bytes, does not matter if it is a text file or binary file. D programming language provides access on high level functions as well as low level (OS level) calls to handle file on your storage devices. Opening Files in D The standard input and output streams stdin and stdout are already open when programs start running. They are ready to be used. On the other hand, files must first be opened by specifying the name of the file and the access rights that are needed. File file = File(filepath, “mode”); Here, filename is string literal, which you use to name the file and access mode can have one of the following values − Sr.No. Mode & Description 1 r Opens an existing text file for reading purpose. 2 w Opens a text file for writing, if it does not exist then a new file is created. Here your program will start writing content from the beginning of the file. 3 a Opens a text file for writing in appending mode, if it does not exist then a new file is created. Here your program will start appending content in the existing file content. 4 r+ Opens a text file for reading and writing both. 5 w+ Opens a text file for reading and writing both. It first truncate the file to zero length if it exists otherwise create the file if it does not exist. 6 a+ Opens a text file for reading and writing both. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended. Closing a File in D To close a file, use the file.close() function where file holds the file reference. The prototype of this function is − file.close(); Any file that has been opened by a program must be closed when the program finishes using that file. In most cases the files need not be closed explicitly; they are closed automatically when File objects are terminated. Writing a File in D file.writeln is used to write to an open file. file.writeln(“hello”); import std.stdio; import std.file; void main() { File file = File(“test.txt”, “w”); file.writeln(“hello”); file.close(); } When the above code is compiled and executed, it creates a new file test.txt in the directory that it has been started under (in the program working directory). Reading a File in D The following method reads a single line from a file − string s = file.readln(); A complete example of read and write is shown below. import std.stdio; import std.file; void main() { File file = File(“test.txt”, “w”); file.writeln(“hello”); file.close(); file = File(“test.txt”, “r”); string s = file.readln(); writeln(s); file.close(); } When the above code is compiled and executed, it reads the file created in previous section and produces the following result − hello Here is another example for reading file till end of file. import std.stdio; import std.string; void main() { File file = File(“test.txt”, “w”); file.writeln(“hello”); file.writeln(“world”); file.close(); file = File(“test.txt”, “r”); while (!file.eof()) { string line = chomp(file.readln()); writeln(“line -“, line); } } When the above code is compiled and executed, it reads the file created in previous section and produces the following result − line -hello line -world line – You can see in the above example an empty third line since writeln takes it to next line once it is executed. Print Page Previous Next Advertisements ”;
D Programming – Loops
D Programming – Loops ”; Previous Next There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow more complicated execution paths. A loop statement executes a statement or group of statements multiple times. The following general form of a loop statement in mostly used in the programming languages − D programming language provides the following types of loop to handle looping requirements. Click the following links to check their detail. Sr.No. Loop Type & Description 1 while loop It repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. 2 for loop It executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. 3 do…while loop Like a while statement, except that it tests the condition at the end of the loop body. 4 nested loops You can use one or more loop inside any another while, for, or do..while loop. Loop Control Statements Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. D supports the following control statements − Sr.No. Control Statement & Description 1 break statement Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. 2 continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. The Infinite Loop A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty. import std.stdio; int main () { for( ; ; ) { writefln(“This loop will run forever.”); } return 0; } When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but D programmers more commonly use the for(;;) construct to signify an infinite loop. NOTE − You can terminate an infinite loop by pressing Ctrl + C keys. Print Page Previous Next Advertisements ”;
D Programming – Immutables
D Programming – Immutable ”; Previous Next We often use variables that are mutable but there can be many occasions mutability is not required. Immutable variables can be used in such cases. A few examples are given below where immutable variable can be used. In case of math constants such as pi that never change. In case of arrays where we want to retain values and it is not requirements of mutation. Immutability makes it possible to understand whether the variables are immutable or mutable guaranteeing that certain operations do not change certain variables. It also reduces the risk of certain types of program errors. The immutability concept of D is represented by the const and immutable keywords. Although the two words themselves are close in meaning, their responsibilities in programs are different and they are sometimes incompatible. The immutability concept of D is represented by the const and immutable keywords. Although the two words themselves are close in meaning, their responsibilities in programs are different and they are sometimes incompatible. Types of Immutable Variables in D There are three types of defining variables that can never be mutated. enum constants immutable variables const variables enum Constants in D The enum constants makes it possible to relate constant values to meaningful names. A simple example is shown below. Example Live Demo import std.stdio; enum Day{ Sunday = 1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } void main() { Day day; day = Day.Sunday; if (day == Day.Sunday) { writeln(“The day is Sunday”); } } When the above code is compiled and executed, it produces the following result − The day is Sunday Immutable Variables in D Immutable variables can be determined during the execution of the program. It just directs the compiler that after the initialisation, it becomes immutable. A simple example is shown below. Example Live Demo import std.stdio; import std.random; void main() { int min = 1; int max = 10; immutable number = uniform(min, max + 1); // cannot modify immutable expression number // number = 34; typeof(number) value = 100; writeln(typeof(number).stringof, number); writeln(typeof(value).stringof, value); } When the above code is compiled and executed, it produces the following result − immutable(int)4 immutable(int)100 You can see in the above example how it is possible to transfer the data type to another variable and use stringof while printing. Const Variables in D Const variables cannot be modified similar to immutable. immutable variables can be passed to functions as their immutable parameters and hence it is recommended to use immutable over const. The same example used earlier is modified for const as shown below. Example Live Demo import std.stdio; import std.random; void main() { int min = 1; int max = 10; const number = uniform(min, max + 1); // cannot modify const expression number| // number = 34; typeof(number) value = 100; writeln(typeof(number).stringof, number); writeln(typeof(value).stringof, value); } If we compile and run above code, this would produce the following result − const(int)7 const(int)100 Immutable Parameters in D const erases the information about whether the original variable is mutable or immutable and hence using immutable makes it pass it other functions with the original type retained. A simple example is shown below. Example Live Demo import std.stdio; void print(immutable int[] array) { foreach (i, element; array) { writefln(“%s: %s”, i, element); } } void main() { immutable int[] array = [ 1, 2 ]; print(array); } When the above code is compiled and executed, it produces the following result − 0: 1 1: 2 Print Page Previous Next Advertisements ”;