This is an old revision of the document!
Highschool workshop - Introduction to D
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.
Compute the median element of an unsorted integer array. For this, you will have to:
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.
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.
Select the (n+1)/2th element.
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:
Store mappings between the name of your team mates and their email address.
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.
What does the code do? Why is it useful to take the address of a parameter?
Add the
@safe attribute to the
main function. What happens?
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.