Table of Contents

Highschool workshop - Introduction to D

Slides

Slides

Exercises

For these exercises you can use the D Online Editor. If you wish to install the D compiler and Standard Library, go to the download page.

1. Array Median Element

Compute the median element of an unsorted integer array. For this, you will have to:

  1. Sort the array: implement any sorting algorithm you wish. At this link you will find a series of searching algorithms, each implemented in its own C file.
  2. Eliminate the duplicates: once the array is sorted, eliminating the duplicates is trivial. The array operations discussed, and more, can be found at this reference.
  3. Select the (n+1)/2th element.
  4. Write unittests to validate your implementation.

Use small functions to increase code readability and testing.

Remember to pass the -unittest argument to the compiler, in order to enable the unittests.

2. The Standard Library

D has a standard library called Phobos. Implement exercise 1 using functions from the std.algorithm package. Use Universal Function Call Syntax (UFCS) for an increase in expressiveness.

3. Dictionaries

Using associative arrays:

  1. Store mappings between the name of your team mates and their email address.
  2. Extend the previous point to also store their phone numbers.

For bullet 2, use a struct, let's call it ColleagueInfo, to wrap their email and phone number.

struct ColleagueInfo
{
    string telefon;
    string mail;
}

Now go ahead and create your <name, ColleagueInfo> dictionary

ColleagueInfo[string] d;

4. @safe

Inspect the source file. Compile and run the code.

  1. What does the code do? Why is it useful to take the address of a parameter?
  2. Add the @safe attribute to the main function. What happens?
  3. How can we get rid of the error messages?

5. Function templates

Write a simple templated function that computes the sum of the elements of an array. Your function should be able to work on any numeric type. This is exactly what we demoed in the presentation.

If you want to read more about D meta-programming, start with this introductory hands-on.