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.

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

size_t numbersSum(T)(T[] numbers)
{
    size_t sum = 0;
    foreach(num; numbers)
    {
        sum += num;
    }
    return sum;
}        
 
void main()
{
    int[] arr = [1, 2, 3, 4, 5];
    writeln(numbersSum!int(arr)); // 15
 
    float[] arr2 = [1.0, 2.0, 3.0, 4.0, 5.0];
    writeln(numbersSum!float(arr2)); // 15
}
size_t numbersSum(T)(T[] numbers)
if (is(T == int) || is(T == float))
{
    size_t sum = 0;
    foreach(num; numbers)
    {
        sum += num;
    }
    return sum;
}
import std.traits : isNumeric;
 
size_t numbersSum(T)(T[] numbers)
if (isNumeric!T)
{
    size_t sum = 0;
    foreach(num; numbers)
    {
        sum += num;
    }
    return sum;
}
dss/workshop-01.1565785171.txt.gz ยท Last modified: 2019/08/14 15:19 by eduard.staniloiu
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0