Programming Language Textbook D. Part 1

Original author: Ali Çehreli
  • Transfer
  • Tutorial
This post begins the series of translations of the D Programming Language Tutorial , in order to compensate for the information vacuum about this system language. Each part will contain a constant amount of material from the book, since the original chapters have a wide range in size: from a couple of paragraphs to several printed pages. All code examples are checked on the current release of the dmd 2.065 compiler , and if there are problems with the technical part, please unsubscribe in the comments.



Other parts:


Acknowledgments


I would like to thank my wife and daughter who survived as many long hours as I wrote the original version in Turkish and also an English translation of this book.

The chapters were initially tested by members of the Turkish Ddili Forum . I am grateful to the Turkish D community for keeping my passion and motivation high.

Mert Ataol, Zafer Çelenk, and Salih Dinçer wrote reviews on almost every line of the book. Can Alpay Çiftçi and Faruk Erdem Öncel played an important role in the development of both books and ddili.org.

Thanks to the following people for their significant corrections, recommendations and ideas: Ergin Güney, Jordi Sayol, David Herberth, Andre Tampubolon, Gour-Gadadhara Dasa, Raphaël Jakse, Andrej Mitrovic, Johannes Pfau, Jerome Sniatecki, Jason Adams, Ali H. Çalışkan, Paul Jurczak, Brian Rogoff, Michael Strashun, Joseph Rushton Wakeling, Tove, Hugo Florentino, Satya Pothamsetti, Luís Marques, Christoph Wendler.

This book was read by Ergin Güney to upgrade my English to normal English.

Introduction


The book is intended to teach the D language of readers who are new to programming. Although experience in other programming languages ​​would undoubtedly be useful, this book begins with the basics. If you are interested in learning to program, I hope you find the book useful.

In order for the book not to be useless, we will need an environment for writing, compiling and running programs in D. This development environment should include at least the following elements:
  • text editor
  • compiler for D


Instead of downloading and installing them separately, you can consider the option with an integrated development environment (IDE). You can find information about editors and the IDE for D on the Editors and IDE pages at dlang.org. Learning to program in D (approx. Yes in general in any language other than pseudocode) without a text editor or compiler is impossible. Instructions for installing the dmd compiler and how to use it will be discussed later in the next chapters.

Each chapter of the book tries to introduce as few new concepts as possible. Most chapters contain several exercises, and there are solutions to them in order to compare your decisions with mine. (Note In this translation, the solutions are under the spoilers next to the tasks.)

I assume that you are not missing chapters. If you come across chapters that are especially hard to give, it may be due to the fact that the book failed to provide all the necessary concepts. Please write to the author (acehreli@yahoo.com) (note leave a comment) about such issues to help make this book more useful.

The book does not disclose programming using a graphical user interface(GUI). Although many programs are much more convenient to use with the GUI, the GUI is not directly related to programming languages. Moreover, design decisions and programming style with GUI can conflict with the style of the language itself and its standard library, and complicate the study of the language. Therefore, the book describes only console programs. Once you learn the basics of D and its standard library, Phobos, you can use any GUI library you want.

Book chapters are available online as you translate from Turkish. You can use the RSS feed to keep abreast of new chapters.

Learning programming is much more fun in a team. Stop by D.learn newsgroupto keep track of discussions and ask questions and answer them.

Programming practice


It is very difficult to determine indisputably what exactly the practice of programming includes, but the craft aspect in it is very strong. Some conclusions about programming:
  • This is the task of creating programs that make the computer behave as expected
  • Since it requires tools and the use of these tools is guided by the experience of master programmers, it is a craft
  • Since it involves resolving constraint problems, it is an engineering skill
  • It is very exciting and satisfying.
  • It is not a fine art, but as far as possible in any human activity, programs can be works of art
  • It is not a science, but the methods used in it are created by computer science.


It can be very difficult to learn and teach programming


Programming has been taught since the 1950s, and effective or successful teaching methods have not yet been developed.

Unfortunately, programming can be challenging for about half of all students. According to a scientific article (note the original link is broken), those who study programming with ease are those who are able to create consistency models to describe new situations that they face.

Some programming difficulties are caused by the number of technical details that need to be learned.

The hello world


The first program in most programming books is the hello world program. This is a very short and simple program that displays “hello world” and ends. This program is important because it includes some basic language concepts.

Below is hello world on D:
import std.stdio;
 
void main ()
{
    writeln ("Hello world!");
}


The source code above must be compiled by the D compiler to create the called file.

Compiler installation


At the time of this writing, you can choose from three D compilers: dmd , a compiler from Digital Mars; gdc , D compiler for GCC; and ldc , a compiler that uses the LLVM infrastructure.

dmd - D compiler that has been used for designing and developing the language for many years. All examples in this book have been tested on dmd . For this reason, the easiest way is to start with dmd and try other compilers if there is a specific need for this (for example, gdc produces the most optimized code).

To install the latest version of dmd go toDigital Mars download page and select a compiler version that fits your computer environment. You must select a dmd version that matches the installed operating system and the batch manager and matches the processor architecture: 32-bit or 64-bit. Do not install the compiler for D1 (approx. The first version is history)! This book covers only D of the second version .

The installation sequence is different for different environments, but it should be as simple as following the simple instructions on the screen and pressing a couple of buttons.

Source code


The file that the programmer writes for compilation is called a source file or simply a source. Since D is a compiled language, the source code itself is not an executable file. The source code must be translated into an executable program by the compiler.

Like all files, the source must have a name. Although this name can be anything that is allowed by the operating system, the .d extension is usually used for files with D source codes, since development environments, programming tools and programmers expect just such an extension. For example, test.d , game.d , invoice.d , etc. Suitable as names for the source.

Hello world compilation


Copy the program text above into a text file and save it under the name hello.d .

The compiler will soon verify the correct syntax of the source code (i.e. for compliance with the rules of the language) and create a program from it by translating it into machine codes. To compile, follow these steps:
  1. Open console window
  2. Go to the directory where hello.d is saved
  3. Enter the following command (Do not write the $ character , it is for the command line.)
    $ dmd hello.d
    

If you have not made mistakes, then it may seem that nothing happened. Otherwise, it means that everything went well. An executable file called hello (or hello.exe for Windows), which has just been created by the compiler, should appear in the folder .

If instead the compiler printed several messages, perhaps you made a mistake when copying the program code. Try to find the error, fix it and restart compilation. You will make many mistakes when programming, so the process of fixing and compiling them will become familiar.

Once the program has successfully created, write the name of the executable file to run it. The program should print “Hello world!”:
$ ./hello     ← запуск программы
Hello world!  ← сообщение, которое она вывела

(note under Windows, hello must be entered instead of ./hello)

Congratulations! Your first D program is working as expected.

Compiler flags


The compiler has many command-line options that are used to influence the compilation process. To see a list of parameters, enter only the name of the compiler:
$ dmd    ← введите только имя
DMD64 D Compiler v2.065
Copyright (c) 1999-2013 by Digital Mars written by Walter Bright
Documentation: http://www.dlang.org/index.html
Usage:
  dmd files.d ... { -switch }
  files.d        D source files
...
  -unittest      compile in unit tests
...
  -w             enable warnings
...


The abbreviated output above shows only the flags that I recommend always to use. Although this does not matter for the hello world program in this chapter, the following command will compile the program with warnings and unit tests enabled . We will consider these and other parameters in more detail in the following chapters:
$ dmd hello.d -w -unittest


A complete list of dmd parameters can be found in the official DMD documentation .

Another flag that might be useful: -run . It compiles the source code, creates an executable file, and runs it in one command:
$ dmd -run hello.d -w -unittest
Hello world!  ← программа автоматически запустилась


IDE


In addition to the compiler, you can install the IDE (integrated development environment). IDEs are designed to simplify program development by simplifying the steps of writing, compiling, and debugging code.

If you install the IDE, compilation and launch of the program will be carried out simply by pressing a keyboard key or button in the IDE. I still recommend that you familiarize yourself with compiling programs manually in the console window.

If you decide to install an IDE, go to the IDE page on dlang.org to see a list of available IDEs (approx. Lane I use DDT).

Hello world analysis


Here is a short list of the many concepts from D that appeared in this short program:

Core: Each language defines its own syntax, fundamental types, keywords, rules, etc. All of them form the core of this language. Parentheses, semicolons, and words such as: main and void are all in accordance with the rules of D. This is similar to the rules of the English (Russian) language: subject, verbs, punctuation, sentence structure, etc.

Keyword: Special words that are part of the core of the language are called key . There are two keywords in this program: import , which is used to connect modules to the program; and voidwhich means "returns nothing."

Library and function: The kernel defines only the structure of the language. It is used to define functions and user types, and they are in turn used to design libraries. A library is a collection of reusable parts of programs that link (note) to your programs to help achieve their goals.

writeln above is a function in the standard library D. It is used to display a line of text, as you might guess from its name: write line - write a line.

Module:The contents of the libraries are collected according to the types of tasks for which they are intended. Such a group is called a module. The only module that our program uses is std.stdio , which is responsible for data input and input.

Symbols and Strings: Expressions such as "Hello world!"are called strings , and string elements are called characters . The only line in this program contains the symbols 'H', 'e', '!'and others.

Execution order: Programs perform their tasks by invoking operations in a specific order. The execution of tasks begins with operations that are written in a function called main . The only operation in our program displays a string"Hello world!".

Case Importance: You can select any characters within the lines, but you must use the rest of the characters exactly as they appear in the program. This is so, since in D programs, case is important. For example, writeln and Writeln are two different names.

We will consider all these features of D in more detail in the following chapters.

Exercises


  • Write a program that outputs something else.
  • Modify the program so that it displays more than one line.
  • Try compiling the program after other changes: for example, remove the semicolon at the end of the line with writeln and study the compilation error.


Solutions
  • import std.stdio;
     
    void main ()
    {
        writeln ("Something else ...: p");
    }

  • import std.stdio;
     
    void main ()
    {
        writeln ("A line ...");
        writeln ("Another line ...");
    }

  • The following program cannot be compiled because there is no semicolon at the end of the line with writeln :
    import std.stdio;
     
    void main ()
    {
        writeln ("Hello world!")
    }




writeln and write


In the previous chapter, we saw that writeln takes a string inside parentheses and prints it.

Parts of a program that actually do the job are called functions, and the information they need to do the job is called parameters . The act of transmitting such information to a function is called passing parameter values to a function. Parameters are passed to the function between parentheses and separated by commas.

The note:The word parameter describes the information that is transferred to the function at a conceptual level. The specific information that is actually transmitted during program execution is called an argument. Although incorrect, these terms sometimes replace each other in the software industry.

writeln can take more than one argument. She prints them sequentially, one by one on the same line:
import std.stdio;
 
void main ()
{
    writeln ("Hello world!", "Hello fish!");
}


Sometimes all the information at once, which should be printed on one line, may be difficult to transmit to writeln . In such cases, the first parts of a line can be printed with write , and the last part with writeln .

writeln goes to the next line, write remains on the same:
import std.stdio;
 
void main ()
{
    //
    Write what we can at the moment write ("Hello");
 
    // ... suppose there are more operations here ...
 
    write ("world!");
 
    // ... and finally:
    writeln ();
}


A call to writeln without parameters just ends the current line.

Lines that begin with //are called comment lines or simply comments . Comments are not part of the code in the sense that they do not affect the behavior of the program. Their sole purpose is to explain what the code does in specific sections of the program. The audience of comments is anyone who can later read the source code, primarily including the programmer who wrote these comments himself.

Exercises


  1. Both programs in this chapter print lines without spaces between them. Change the program so that there are spaces between the arguments, as in "Hello world!"
  2. Also try calling write with more than one parameter.


Solutions
  1. One method is to use another parameter in the middle:
    writeln ("Hello world!", "", "Hello fish!");


  2. write can also take several parameters:
    write ("one", "two", "three");



Also popular now: