Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

Learning D
Learning D
Learning D
Ebook1,007 pages7 hours

Learning D

Rating: 0 out of 5 stars

()

Read preview

About this ebook

This book is intended for those with some background in a C-family language who want to learn how to apply their knowledge to D. Perhaps you're a college student looking to use D for hobby projects, or a career programmer interested in expanding your skillset. This book will help you get up to speed with D and avoid common pitfalls that arise when translating C-family experience to D.
LanguageEnglish
Release dateNov 27, 2015
ISBN9781785289347
Learning D
Author

Michael Parker

Michael Parker is responsible for Intel’s FPGA division digital signal processing (DSP) product planning. This includes Variable Precision FPGA silicon architecture for DSP applications, DSP tool development, floating point tools, IP and video IP. He joined Altera (now Intel) in January 2007, and has over 20 years of previous DSP engineering design experience with companies such as Alvarion, Soma Networks, Avalcom, TCSI, Stanford Telecom and several startup companies. He holds an MSEE from Santa Clara University, and BSEE from Rensselaer Polytechnic Institute.

Read more from Michael Parker

Related to Learning D

Related ebooks

Internet & Web For You

View More

Related articles

Reviews for Learning D

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Learning D - Michael Parker

    Table of Contents

    Learning D

    Credits

    Foreword

    About the Author

    About the Reviewers

    www.PacktPub.com

    Support files, eBooks, discount offers, and more

    Why subscribe?

    Free access for Packt account holders

    Preface

    What this book covers

    What you need for this book

    Who this book is for

    Conventions

    Reader feedback

    Customer support

    Downloading the example code

    Errata

    Piracy

    Questions

    1. How to Get a D in Programming

    Say hello to D

    An introductory program

    Getting help

    The Digital Mars D compiler

    Frontends, backends, and linkers

    Installing DMD

    The Windows installer

    Installing from the ZIP

    The Windows ZIP

    The POSIX ZIPs

    Compiling the example

    Documentation and source code

    The documentation

    The source

    Say hello to MovieMan

    The problem

    The features

    DUB – the D build tool and package manager

    Getting started

    Configuring the MovieMan project

    Understanding dub.sdl

    Building and running MovieMan

    Changing the output directory

    Summary

    2. Building a Foundation with D Fundamentals

    The very basics

    Identifiers

    A note about scope

    More on modules

    Module declarations

    More about import declarations

    The special package module

    Comments

    Variable declaration and initialization

    Basic types

    The types

    Literals

    Integer literals

    Floating-point literals

    Character literals

    Conversions

    Alias declarations

    Properties

    Basic operators

    Arithmetic operators

    Bitwise operators

    Relational and logical operators

    The cast operator

    Derived data types

    Pointers

    Arrays

    Array basics

    Rectangular arrays

    Slices

    Array literals

    Arrays and void

    Array operations

    Strings

    String essentials

    Alternative string literals

    WYSIWYG strings

    Delimited strings

    Token strings

    Associative arrays

    Control flow statements

    Traditional loops

    The foreach loop

    Traditional conditionals

    The goto statement

    Type qualifiers – const and immutable

    The contracts

    With the basic types

    With pointers

    With arrays

    Conversions

    Functions

    Overloaded functions

    ref and out

    inout parameters

    lazy parameters

    Function attributes

    Return statements and memory

    Function pointers and delegates

    MovieMan – first steps

    The io module

    The app module

    Summary

    3. Programming Objects the D Way

    User-defined types

    Enumerations

    Unions

    Structs and classes

    Working with objects

    Encapsulation with protection attributes

    Public

    Private

    Package

    Voldemort types

    Constructors and destructors

    Class constructors and destructors

    Struct constructors and destructors

    Static constructors and destructors

    Inheritance and polymorphism

    Interfaces

    Fake inheritance

    Nested classes

    Objects with const and immutable

    const as a storage class

    Error handling

    Scope guards

    Exception handling

    Contract programming and unit tests

    Assert contracts

    Function contracts

    Invariants

    Unit tests

    MovieMan – adding menus

    The Menu base class

    The MainMenu class

    The DisplayMenu class

    Summary

    4. Running Code at Compile Time

    Pragmas

    The lib pragma

    The msg pragma

    The inline pragma

    Conditional compilation

    The version condition

    The debug condition

    The static if condition

    Compile-time strings

    The import expression

    String mixins

    Compile-time function execution

    Odds and ends

    static assert

    The is expression

    Alignment

    Compile-time reflection

    User-defined attributes

    Summary

    5. Generic Programming Made Easy

    Template basics

    Templates as code blocks

    Struct and class templates

    Enum templates

    Function templates

    Special features

    More template parameters

    Value parameters

    Alias parameters

    This parameters

    Beyond the basics

    Template specializations

    Specialization on pointers and arrays

    Template constraints

    Template mixins

    Variadic templates

    Terminology

    More on usage

    Operator overloading

    Non-templated operator overloads

    Comparison overloads – opEquals and opCmp

    opEquals

    opCmp

    Considerations

    Function call overloads

    Assignment overloads

    Index overloads

    opIndex

    opIndexAssign

    opDollar

    Templated operator overloads

    Unary overloads

    Binary overloads

    Cast overloads

    Operator assignment overloads

    Slice operator overloads

    Other overloads

    opDispatch

    opApply

    toHash

    MovieMan – the database

    db.d

    Back to the menus

    Summary

    6. Understanding Ranges

    Ranges defined

    The problem

    The solution

    The interface

    A range for arrays

    The implementation of filter

    The test

    The real ranges

    Input ranges

    Forward ranges

    Bidirectional ranges

    Random-access ranges

    Output ranges

    Optional range primitives

    hasLength

    isInfinite

    Other options

    Ranges in use

    Custom ranges

    Getting a range from a stack

    A name generator range

    Other considerations

    Custom algorithms

    Summary

    7. Composing Functional Pipelines with Algorithms and Ranges

    Functional programming and composable pipelines

    A simple example

    A more complex example

    Sometimes we can't

    Navigating Phobos

    std.range

    Generative ranges

    iota

    recurrence

    sequence

    Selective ranges

    take

    drop

    stride

    retro

    Compositional ranges

    chain

    roundRobin

    transposed

    zip

    lockstep

    std.algorithm

    Comparison

    equal

    cmp

    mismatch

    levenshteinDistance

    Iteration

    group

    map

    reduce

    Mutation

    copy

    fill

    remove

    Searching

    find

    count

    any

    Set operations

    setIntersection

    setDifference

    setUnion

    Sorting

    sort

    partition

    std.array

    Appender

    assocArray

    join

    Where to look for more

    MovieMan – wrapping up

    The db module

    The display menu

    Making it better

    Summary

    8. Exploring the Wide World of D

    Online resources

    DWiki

    Planet D

    reddit and StackOverflow

    This Week in D

    DConf

    DSource

    Editors and IDEs

    Text editors

    Vim and Emacs

    Textadept

    Sublime Text

    IDEs

    Visual D

    Mono-D

    DDT

    Code::Blocks

    Tools and utilities

    DMD

    Optimized and debug builds

    Changing the default output

    Compiling libraries

    Using libraries

    Warnings

    Profiling

    Code coverage analysis

    Compile and run

    GDC and LDC

    GDC

    LDC

    RDMD

    DustMite

    DCD

    DVM

    Libraries

    code.dlang.org

    Using libraries from the DUB registry

    Registering libraries with the DUB registry

    Browsing the DUB registry

    Deimos and DerelictOrg

    Summary

    9. Connecting D with C

    Preliminaries

    Terminology

    Bindings, wrappers, and ports

    Dynamic and static – context matters

    Static libraries and static linking

    Dynamic libraries and dynamic linking

    Dynamic and static bindings

    Object file formats

    Linkage attributes

    Name mangling

    Calling conventions

    Putting it together

    Binding D to C

    Function prototypes

    Manually loading shared libraries

    Trying it out

    C types to D types

    Strings and characters

    Special types

    Enumerations

    Structures

    Pointers

    Type aliases

    Function pointers

    Defined constants

    Function parameters and return types

    Symbols

    Global variables

    Macros

    Conditional compilation

    Calling C from D

    D arrays and C arrays

    Basic arrays

    Arrays of arrays

    Strings

    Memory

    C callbacks and exceptions

    Calling D from C

    Summary

    10. Taking D Online

    The software

    vibe.d

    Package overview

    The anatomy of a vibe.d web app

    The database library

    MovieManWeb

    Getting started

    The basics of diet templates

    Tags and indentation

    Including and extending templates

    The MovieManWeb layout

    Setting up the database

    Fleshing out the index page

    Mapping web interface functions to URLs

    Rendering diet templates

    Rewriting index.dt

    Adding movies

    Implementing the addMovie function

    Implementing the postAdd function

    Implementing add.dt

    Modifying index.dt

    Modifying app.d

    Modifying layout.dt

    Listing movies

    Implementing the listMovies function

    Modifying the index function

    Modifying index.dt

    Finding movies

    Implementing the postFind function

    Implementing find.dt

    Modifying index.dt

    Modifying app.d and layout.dt

    Implementing the findMovie functions

    findMovie the first

    findMovie the second

    Editing and deleting movies

    Expanding on MovieManWeb

    Summary

    11. Taking D to the Next Level

    Concurrency

    Threads and fibers

    Threads

    Fibers

    Data sharing

    __gshared

    Shared

    Synchronization and atomics

    Automatic synchronization

    Manual synchronization

    Atomics

    Message passing

    Parallelism

    More information

    SafeD

    Functional purity

    The garbage collector

    Connecting with C++

    More on Phobos

    std.container

    std.datetime

    std.digest

    std.experimental

    std.getopt

    std.process

    std.socket

    Modules for Unicode and other encodings

    System bindings

    Game development with D

    The future of D

    Summary

    Index

    Learning D


    Learning D

    Copyright © 2015 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    First published: November 2015

    Production reference: 1241115

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham B3 2PB, UK.

    ISBN 978-1-78355-248-1

    www.packtpub.com

    Credits

    Author

    Michael Parker

    Reviewers

    John Loughran Colvin

    Jonathan M Davis

    Kingsley Hendrickse

    David Nadlinger

    Steven Schveighoffer

    Ilya Yaroshenko

    Commissioning Editor

    Akhram Hussain

    Acquisition Editor

    Reshma Raman

    Content Development Editor

    Merwyn D'souza

    Technical Editor

    Vivek Arora

    Copy Editor

    Imon Biswas

    Project Coordinator

    Neha Bhatnagar

    Proofreader

    Safis Editing

    Indexer

    Rekha Nair

    Production Coordinator

    Melwyn Dsa

    Cover Work

    Melwyn Dsa

    Foreword

    How far things have come! I started D in 1999. The odds of any new programming language endeavor succeeding were minimal.

    But here we are with the latest book on D, Learning D by Michael Parker.

    The arc of programming languages I've learned follows a consistent pattern – my first Fortran code looked a lot like Basic. My first C code looked similar to Fortran. C++ code looked similar to C, and my early D code looked similar to C++. It takes some time to get used to a language before learning its own idiomatic style, and this is what it takes before the source code starts to shine.

    After all, if your D code looks similar to C++, what's the point?

    Learning D fills the need to get up-to-speed quickly by explaining how to write code in a way that fits in perfectly with D's combination of characteristics. Far from being a dry technical specification, Michael writes about D from a more personal perspective, as you'd expect from someone tutoring you. He lists how to use the features, how they compare with other languages, and offers best practices. He offers background anecdotes and explanations for why some things are the way they are, and how D has evolved, which can be surprisingly helpful in using the language more effectively.

    D has been characterized in many ways, but my favorite is that it is designed to be fun to program in. After all, programming being our profession, isn't it better when we enjoy our tools?

    I know this book is a labor of love from Michael, as the language itself is a labor of love from myself and the rest of the D community. I hope this joy is successfully imparted to you, the reader and programmer. I'm sure that Michael and I would be well rewarded for our endeavors if this is the case.

    Enjoy!

    Walter Bright

    Creator of the D Language and Engineer

    About the Author

    Michael Parker created the popular D library collection, Derelict, in 2004, and has been the primary maintainer ever since. He also blogs about the language at The One with D, and is a coauthor of the book Learn to Tango with D, Apress. He lives in Seoul, South Korea, with his wife, Mi Kyoung, and their dogs, Charlie, Happy, Joey, and Toby.

    This is the first book on which I've been the sole author, but no author works alone. Without the professional assistance of my editors, Merwyn D'souza and Reshma Raman, I would have been lost at sea. I'd hate to admit how many errors would have persisted without the expert feedback of the technical reviewers, John Colvin, Jonathan Davis, Kingsley Hendrickse, David Nadlinger, Steven Schveighoffer, and Ilya Yaroshenko. They have all helped make this a much better book than it otherwise would have been; the blame for any remaining technical errors that may surface rests squarely on my shoulders.

    I'd like to offer a great deal of gratitude to all of the active members of the D community who participate in the D forums, helping both newbies and old-timers alike in overcoming confusion and solving problems. I'd especially like to thank Ali Çehreli and Adam D. Ruppe, whose own writings and posts in the newsgroups helped to clarify some issues I had in exploring corners of D I had rarely touched before writing this book. Thanks also to Walter Bright and Andrei Alexandrescu, both of whom have made a number of sacrifices to further the development of this wonderful programming language.

    Finally, I could never have expended the time and energy on this book that I did without the support of my wife, Mi Kyoung. I owe her a great many missed dinners and canceled events, along with my everlasting thanks and love.

    About the Reviewers

    John Loughran Colvin is an avid programmer and active member of the D community with multiple projects in flight, including a collaboration aiming to build a comprehensive base for scientific programming in D (http://dlangscience.github.io/).

    I would like to thank friends and family who keep me sane while I do all this!

    Jonathan M Davis is the primary author of std.datetime in D's standard library, Phobos, and is one of Phobos' core contributors. He is a professional developer and has experience in a number of programming languages, including C++, Haskell, Java, and D. For better or worse, he's well known in the D community for answering questions and being long-winded. He currently resides in California.

    Kingsley Hendrickse is a polyglot software developer who specializes in building software using agile principles. His career began in the late '90s where he focused primarily on functional and automated testing but gradually expanded into agile and software engineering while working at ThoughtWorks.

    After many years programming in Ruby and Java, he was introduced to the D language while looking for new challenges. He has a wide range of development interests and is currently focusing on web development using Scala, D, and JavaScript using a functional programming style.

    He has spent the last decade working for a wide range of prominent banking and financial companies.

    Steven Schveighoffer has a bachelors degree in computer science from WPI, and has 16 years of experience working on various systems from small microcontrollers to enterprise servers. He has been active in the D community since 2007 and has made several major contributions to the D language and runtime.

    Steve is a principal software engineer at National Resource Management Inc., an energy savings company (http://www.nrminc.com/).

    www.PacktPub.com

    Support files, eBooks, discount offers, and more

    For support files and downloads related to your book, please visit www.PacktPub.com.

    Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at for more details.

    At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

    https://www2.packtpub.com/books/subscription/packtlib

    Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

    Why subscribe?

    Fully searchable across every book published by Packt

    Copy and paste, print, and bookmark content

    On demand and accessible via a web browser

    Free access for Packt account holders

    If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.

    Preface

    Walter Bright first released the D programming language into the wild on December 8, 2001. Three weeks later, seven more iterations of the compiler had been uploaded to the Digital Mars website, incorporating fixes for bugs reported by users who had already begun experimenting with this exciting new language. In the years since, enthusiasts have continued to actively participate in D's development, pushing the language through two major versions and numerous compiler releases. D is very much a community-driven programming language.

    This book aims to bring you up to speed with D to the degree that you can be confident in developing your own D programs and, if you are so motivated, participate in activities that drive the language forward. It is assumed that you already have some familiarity with other languages similar to D, such as C++ or Java, and have some familiarity with working with the command line. With this in mind, fewer details will be given for the features of D that are similar to those of other C-family languages and no instructions will be given on how to perform basic command-line tasks, such as changing directories or setting the system path.

    What this book covers

    Chapter 1, How to Get a D in Programming, introduces you to the D programming language and provides instructions for setting up the DMD compiler and the DUB build tool and package manager.

    Chapter 2, Building a Foundation with D Fundamentals, gives an overview of all of D's foundational features, such as basic types, loop constructs, flow control, and more.

    Chapter 3, Programming Objects the D Way, discusses D's support for object-oriented programming, including aggregate types and interfaces.

    Chapter 4, Running Code at Compile Time, provides a tutorial on the compile-time aspects of D, including its support for Generative Programming and CTFE (Compile-Time Function Evaluation).

    Chapter 5, Generic Programming Made Easy, explores the basics of D's support for Generic Programming, including templates, template constraints, and mixins.

    Chapter 6, Understanding Ranges, introduces the Range concept, which serves as the core of D's support for functional programming.

    Chapter 7, Composing Functional Pipelines with Algorithms and Ranges, explores several range-based functions in the standard library that can be used to write functional-style code and reduce memory allocations.

    Chapter 8, Exploring the Wide World of D, looks at the D ecosystem, highlighting specific websites, tools, and third-party libraries.

    Chapter 9, Connecting D with C, references how to create D bindings for C libraries to take advantage of existing codebases.

    Chapter 10, Taking D Online, introduces the asynchronous, event-driven networking and web app framework, vibe.d, through the development of a sample project.

    Chapter 11, Taking D to the Next Level, provides a quick look at other language and library features that can serve as a starting point for further exploration of the D programming language.

    What you need for this book

    To compile the code examples in this book, you will need DMD 2.068 or a later version. To compile the sample projects, you will also need DUB 0.9.24 or a later version. Installation instructions for both are provided in the first chapter.

    In order to download dependencies, the color example in Chapter 8, Exploring the Wide World of D, and the sample project in Chapter 10, Taking D Online, requires an Internet connection the first time they are compiled.

    Who this book is for

    This book is intended for those with some background in a C-family language who want to learn how to apply their knowledge and experience to D. Perhaps you're a college student looking to use D for hobby projects, or a career programmer interested in expanding your skillset. This book will help you get up to speed with the language and avoid common pitfalls that arise when translating C-family experience to D.

    Conventions

    In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

    Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: An anonymous enum declaration does not declare a new type.

    A block of code is set as follows:

    void healthBasedSwap(int[] squad1, int[] squad2) {

      import std.algorithm : sort, SwapStrategy;

      import std.range : chain;

      squad1.chain(squad2).sort!((a,b) => a > b,

      SwapStrategy.unstable)();

    }

    When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    void healthBasedSwap(int[] squad1, int[] squad2) {

      import std.algorithm : sort, SwapStrategy;

      import std.range : chain;

     

    squad1.chain(squad2).sort!((a,b) => a > b,   SwapStrategy.unstable)();

     

    }

    Any command-line input or output is written as follows:

    dmd hello.d

    Note

    Warnings or important notes appear in a box like this.

    Tip

    Tips and tricks appear like this.

    Reader feedback

    Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

    To send us general feedback, simply e-mail <feedback@packtpub.com>, and mention the book's title in the subject of your message.

    If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

    Customer support

    Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

    Downloading the example code

    You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

    Errata

    Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

    To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

    Piracy

    Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

    Please contact us at <copyright@packtpub.com> with a link to the suspected pirated material.

    We appreciate your help in protecting our authors and our ability to bring you valuable content.

    Questions

    If you have a problem with any aspect of this book, you can contact us at <questions@packtpub.com>, and we will do our best to address the problem.

    Chapter 1. How to Get a D in Programming

    Before diving into the core features of the D programming language, some laying of groundwork is in order. This first chapter serves as a gentle introduction to D and as a guide to installing the prerequisite tools of the trade we'll be using throughout the book. The example program shown here isn't anything earth-shatteringly amazing, but it does demonstrate a couple of features of D that do not exist in other languages. The sample project that is developed over the course of the book is also introduced here, with a look at the motivation behind it and the features that will be implemented. Here's what you can expect to see:

    Say hello to D: This examines a simple D program and gives you advice on where to go for help with D

    The Digital Mars D compiler: This covers how to install and run DMD

    Say hello to MovieMan: This is an introduction to the two versions of the sample project developed throughout the book

    DUB—the D build tool and package manager: This covers how to install DUB and configure it to build the first version of MovieMan

    Say hello to D

    The D programming language is a multi-paradigm language that belongs to the C family. Out of the box, it supports aspects of procedural, object-oriented, generic, generative, and functional programming. That's not to say that it's an OOP language or a functional programming language, or that it can accurately be pigeonholed into any specific paradigm. The philosophy of D is to provide a range of tools that allow the programmer to have efficiency, control, and modeling power while ensuring that all of the disparate parts work smoothly together. Use object orientation where you need it, but forgo it for procedural or functional programming in other areas of your code base and be assured that it will all work together as a cohesive whole. Many D programmers will tell you that there isn't one specific feature of D that, taken in isolation, makes the language a pleasure to use. Rather, it's the sum of all the parts that keeps them writing D code.

    New users coming to D from other C-family languages will find a great deal that looks familiar. That can be reassuring and makes for a good head start on learning some of D's features; caution is warranted, however. It's tempting to take that familiarity for granted and try to write D as if it were a more familiar language. For the most part, things will work as expected. D is, after all, a member of the C family. But in some cases, this is certain to lead to unexpected compiler errors, or the realization that some blocks of code aren't behaving in the manner the new D user thinks they should. In other cases, there is a more idiomatic D approach that can improve readability or maintainability, particularly when working with the standard library.

    To learn a new language effectively, it's necessary to come at it with as close to a blank slate as possible. Just because features look the same on the surface as they do in another language, doesn't mean they are the same underneath. Given that premise, a consistent theme in this book is that D is not C++, Java, C#, or any language other than D. When you are writing D code, you should be thinking in D. Several of the code snippets in the book are intended not just to introduce D features, but to demonstrate explicitly how certain features differ from other languages. You are encouraged to enter such snippets into an editor yourself, especially if C++ is already in your muscle memory. Implementing the snippets as you encounter them and seeing the differences in action makes it more likely that you'll think in D instead of C++ when working on your own D projects.

    Note

    D started life as the Mars programming language, but Walter's friends kept calling it D. Eventually, he began to do so as well and the name stuck (see the D FAQ at http://dlang.org/faq.html#q1 for background). Neither name lends itself to productive web searches, but search engines are able to recognize the keyword dlang. Use that in your list of search terms rather than simply using D and you should be rewarded with a number of relevant hits.

    An introductory program

    This section presents a simple D program demonstrating a handful of language and library features. A brief description of each feature is then given, along with a reference to the chapter in which it is explained in more detail. Anyone familiar with C should be able to follow the code rather easily, though there might be a couple of features that seem unusual. If you happen to find any of it confusing, don't worry about it for now. Each feature will be explained later in the book.

    In preparation for implementing all of the code snippets and examples in this book, it's a good idea to create a directory somewhere that's easy to navigate to from the command line—for example C:\LearningD or ~/learningd. However you choose to name this directory, it will be referred to as $LEARNINGD throughout the book. Each chapter should have its own subdirectory. The example in this section should be saved as $LEARNINGD/Chapter01/hello.d.

    Note

    Note that I prefer to use forward slashes when I type source paths, unless I'm talking specifically about Windows, which means Windows users should convert them to backslashes as needed.

    Let's look at the example now:

    import core.thread;

    import std.stdio;

    void main() {

        import std.range : iota, retro;

        write(Greeting in );

        foreach(num; iota(1, 4).retro) {

            writef(%s..., num);

            stdout.flush();

            Thread.sleep(1.seconds);

        }

        writeln();

        writeln(Hello world!);

    }

    The first thing to understand is that all D source files serve a purpose beyond just being text files on your computer. A D source file is also a D module. Most D users use the terms source file and module interchangeably. A module is one of several levels of encapsulation in a D program (we'll talk more about encapsulation in Chapter 3, Programming Objects the D Way). If you compile a D source file named hello.d, then the compiler will read it into memory and your program will contain a single module named hello. This is the default behavior. Since we are implementing a simple one-module program, we'll just accept the default and put off learning how to override it until Chapter 2, Building a Foundation with D Fundamentals.

    The first two lines of the example look like this:

    import core.thread;

    import std.stdio;

    An import declaration tells the compiler to look up a given module, specified by the name immediately following the import keyword, and then make some or all of its symbols available within a specific section of the current module. In the format we use here, in which no symbols are specified, all publicly visible symbols in the imported module are made available. The location of the declaration is what determines the section, or scope, in which the symbols will be available. In this case, since the declarations are in module scope and no specific symbols are listed, the net effect is that every publicly visible symbol in the core.thread and std.stdio modules is available for use throughout the entirety of our hello module.

    Consider the module name std.stdio. Each part of the name has a defined meaning. Although the term module name is used to refer to the full name, the part to the right of the dot, stdio, is the actual module name. The part to the left of the dot, std, is the name of a package. Packages are used to group modules into hierarchies. A module can belong to only one package, but that package can be a subpackage of another package, which can be a subpackage of another package, and so on. This means you can have multiple package names on the left side of the dot, such as mylib.data.formats.json. Here, we have three packages and are referring to a module called json. The package named formats is a subpackage of data, which is a subpackage of the top-level, or root, package called mylib. There's more to say about modules and import declarations in Chapter 2, Building a Foundation with D Fundamentals.

    The std and core packages are available with any D compiler; the former is part of Phobos, the D standard library, and the latter is part of the runtime library, DRuntime. std.stdio makes available everything needed for basic file I/O, including reading from standard input (stdin) and writing to standard output (stdout). The module core.thread provides facilities for creating new threads and affecting the execution of the current thread.

    Now take a look at the next line:

    void main() {

    Every D program requires a function named main. When a program is first launched, control passes from the operating system to the C runtime and from there to the D runtime. Finally, main is called and the program takes control. We'll look at this in a little more detail in Chapter 3, Programming Objects the D Way, when we'll also see that it's possible to execute code before main is called.

    There are four fundamental alternatives for declaring a main function. Which one to choose is entirely dependent on the requirements of the program:

    void main() {}

    void main(string[] args) {}

    int main() { return 0; }

    int main(string[] args) { return 0; }

    The first two versions are ultimately equivalent to the latter two; the compiler will ensure that they actually return 0 upon successful execution. Execution is considered to fail when an exception is thrown (exceptions are introduced in Chapter 3, Programming Objects the D Way). For most of the examples in this book, the first signature is all we need. Except for a couple of snippets later on, we aren't going to parse any command line arguments, so we can dispense with forms that accept an array of strings. We also aren't writing any programs that need to pass a return value to the OS on exit, so we have no need of the versions with the int return.

    Note

    Windows programmers might be wondering how D handles WinMain. DRuntime knows only of main, so if WinMain is used as the program entry point, then all of the initialization normally carried out by DRuntime must be handled manually. We'll learn more about DRuntime later.

    Let's get back to the code. The next line is another import declaration, one which differs from the two declarations at the top of the module:

    import std.range : iota, retro;

    Because this declaration is inside a function, it is called a scoped import. Symbols made visible by scoped imports are only visible inside the scope in which the declaration is made. In this case, the symbols are visible only inside main. There's more to this declaration, though. Notice the colon, followed by iota and retro. In an import declaration, a colon followed by a comma-separated list of symbols means that only the listed symbols will be visible. In this case, no symbols from std.range are visible in main other than iota and retro. We'll see what they do shortly.

    It's time for a line that actually puts something on the screen. For that, we're going to invoke a handy and very flexible function from the std.stdio module:

    write(Greeting in );

    The write function is one of a handful of functions that print text strings to standard output. It's analogous to the C standard library function puts, but it differs in that it can take any number of arguments of any type. Each argument will be printed in the order they are given to the function, with no spaces added between them. For example:

    write(Happy , 100, th birthday to, you!)

    This prints the text Happy 100th birthday to you!.

    The next line introduces three items:

    foreach(num; iota(1, 4).retro) {

    The foreach loop is a loop construct that can be used to iterate over a range. iota is a function that returns a range of numbers, in this case from 1 to 3. retro is a function that takes a range as input and returns a new one containing the elements of the original range in reverse order. The ultimate result of this line is a loop iterating over the numbers 3, 2, 1. The foreach loop is described in Chapter 2, Building a Foundation with D Fundamentals. The entirety of Chapter 6, Understanding Ranges, is devoted to explaining ranges, an integral part of D. Both the iota and retro functions are described in Chapter 7, Composing Functional Pipelines with Algorithms and Ranges.

    It's worth noting here that iota(1, 4).retro is the same as retro(iota(1, 4)). The former syntax is possible because of a feature called Uniform Function Call Syntax (UFCS). Given a function func and a function argument arg, func(arg) can be written as arg.func(). You'll learn more about UFCS in Chapter 2, Building a Foundation with D Fundamentals.

    Next up are the three lines of the foreach loop:

    writef(%s..., num);

    stdout.flush();

    Thread.sleep(1.seconds);

    The writef function is a variation of write that prints a formatted text string to standard output. It's analogous to the C standard library function printf; with .stdout is a global instance of a type called File, both of which are declared in std.stdio.

    When writing to a file handle, the operating system buffers text internally for efficiency. Normally, when the handle belongs to a console or terminal, line buffering is enabled. This means that the buffer is flushed when a newline character is printed to the output stream. In this example, calling flush manually flushes the buffer in order to achieve the effect of having one number printed per second; otherwise, it would all be printed at once after the loop exits and the first call to writeln executes. This effect is regulated by the call to Thread.sleep, which causes execution of the process to pause for one second.

    Note that the call to Thread.sleep is not using UFCS. Thread is a class, and sleep is a static member function. 1.seconds, however, does use UFCS. The function seconds is declared in a runtime module named core.time. This module is imported indirectly by core.thread such that all of its symbols are visible. 1.seconds is the same as seconds(1) (parentheses on function calls are sometimes optional). This function returns an instance of the Duration type, which sleep uses to determine how long to pause the current thread. Public imports and function call syntax are discussed in Chapter 2, Building a Foundation with D Fundamentals. Classes and member functions are introduced in Chapter 3, Programming Objects the D Way.

    Finally, the last two lines of the example:

    writeln();

    writeln(Hello world!);   

    The writeln function is identical to write, but has one additional feature: it appends a newline character to the output. Here, we call it twice. The first call appends a newline to the text that was written in the loop, while the second prints the greeting. This could be condensed to one line as writeln(\nHello world!). Note that there is also a formatting version of this function called writefln.

    In order to verify that this program works as expected, it will need to be compiled and executed. Instructions on how to do so will be discussed later in the chapter.

    Getting help

    In your journey with D, you're inevitably going to need assistance. There are a couple of primary online locales where experienced D users can be found answering questions from not-so-experienced D users and having fierce debates about language features, as passionate programmers are known to do.

    The first place any new D user should look is http://forum.dlang.org/. This isn't a self-contained forum as the URL implies, but rather a web interface to a newsgroup server maintained by Digital Mars. If you ever find yourself wondering why you can't edit or delete posts in the D forums, this is why. The forum targeting new users is digitalmars.D.learn, project and major news announcements are made in digitalmars.D.announce, while digitalmars.D is where you can go to witness or participate in discussions about the state of the language and its future direction. As you become more familiar with D and its ecosystem, some of the other forums might start to be of interest to you.

    Note

    The web interface called DFeed was developed in D by an active community member named Vladimir Panteleev. You can find the source for DFeed at https://github.com/CyberShadow/DFeed.

    If the web interface doesn't do it for you, there are other options to access the forums. Given that the primary backend is a newsgroup, you can set up an account in a newsgroup reader for news.digitalmars.com and select the newsgroups you're interested in following. Alternatively, you can point your browser at http://lists.puremagic.com/mailman/listinfo and subscribe to forums of interest via the mailing list interface. Again, the mailing lists are collectively an alternative interface to the newsgroups and not a completely independent entity.

    Tip

    The D community is generally helpful and friendly to those asking questions in the digitalmars.D.learn forum. You should never feel hesitant about asking questions in the D forums. Experienced users drop by regularly, willing to answer the most basic questions. You can also find a number of D users idling in the #D IRC channel. If you have an IRC client, #D is located at http://freenode.net/. Anyone there can answer your questions about D. I've never been much of an IRC user, but I do drop by #D now and again. Whenever I'm around, I'll be happy to answer questions about this book or any of my other D projects. I'm usually found under the handle aldacron in IRC and my real name in the forums.

    The Digital Mars D compiler

    DMD is the reference compiler for the D programming language. Created by Walter Bright, it is still maintained by him with the help of a handful of talented volunteers. It's not the only D compiler out there. GDC is built on top of the GNU Compiler Collection (GCC) and LDC uses the LLVM toolchain. Both compilers were created, and continue to be maintained, by members of the D community. As you write more D code, you'll find that DMD has blazingly fast compile times, while GDC and LDC produce highly optimized executables that tend to have better performance (though they are far from slow in terms of compilation speed). Because of this, it's not uncommon for D programmers to use DMD during development of a new project to take advantage of the faster compile times, then use one of the other compilers to build the final release and benefit from the more advanced optimizations. That said, we're going to be focused exclusively on DMD in this book. The code snippets and the sample project should compile with GDC or LDC just fine, but any compiler-specific instructions in the text will be for DMD.

    There is nothing complex about installing DMD. Before we make that happen, it's important to understand a couple of things about how DMD works.

    Frontends, backends, and linkers

    One of the primary goals Walter established during D's early development was that it must be binary-compatible with C. Essentially, this means that it should be possible to compile a C source file with a C compiler and combine the output into a program that is written in D and compiled with a D compiler, or vice versa. To achieve this goal, output from a D compiler has to be in a format that C toolchains can understand. An in-depth discussion of compiler technology is quite a long way beyond the scope of this book, but it's necessary to have a minimal understanding of a small part of it in order to make DMD work for you more effectively.

    Compilers typically have two

    Enjoying the preview?
    Page 1 of 1