On Saturday, 7 June 2014 at 06:48:39 UTC, Philippe Sigaud wrote:
I was watching Chuck Allison talk yesterday, and wondered what could be a possible homework in D. Maybe other people here have some ideas, maybe Bearophile will point to RosettaCode, I don't know. But here is a possible idea:

Trees.

Since you taught them about ranges/lists and functional mapping/filtering/folding on them, maybe an opening towards trees could be interesting. Trees are present everywhere as a structure: documents, initialization files, even source code. Defining a generic, polymorphic, tree node is easy in D:

struct Tree(T)
{
    T value;
    Tree[] children;
}

There. Not much more complicated than T[], right?
Have them play with factory functions, assembling trees together and so on. Writing a way to print a tree on the console is also fun.

Then, show them how to map a function on a tree, to get a different tree with the same shape:

Tree!int tree1 = ...

Tree!string tree2 = treeMap!((int i)=> to!string(i))(tree1);

Then, ask them why there is no (easy) way to filter a tree :)

And, reduce. Reducing a tree is very powerful. Getting its height, the number of nodes. Show to them that the printing function they wrote to get trees on screen is in fact a reduce.

And now for the fun part, what could be a real assignment (is that the US word?): encode a document as a tree.

Maybe like this:

enum MarkUp { text, title, section, emphasis, ... }

struct DocNode
{
    MarkUp nodeType;
    string content;
    DocNode[] children;
}

So a doc is a root node, probably a section, containing other subsection, and so on. And the assignment is: write different functions to output the tree content as HTML, XML, DocBook, LaTex, Wikipedia mark-up or markdown. Of course, that should use map/reduce :) Outputting something that can be seen on their browser should interest them.

Of course, if at this stage they already know parsing (from the compiler course), they can also create the tree by parsing an input text in a simple markup language, and then converting into another format, all of that using D. But maybe that's too complicated?


Thoughts? Do other people here have homework ideas?

I did that for a project at work. A generic tree with specific DOM implementation. It's a simple concept, yet interesting, especially when you get a chance to eliminate JS's shortcomings.

I split it up though. I have a generic Tree(T) that takes child nodes of various types like this:

struct / class Element(T) {
  T name;
  T[T] attributes;
  // ...
  string toString() {
    return ...;
  }
}

So each element manages / can look at its own data, and the Tree(T) is just an interface that manages these elements and exposes methods like "getElementsByTagName" etc. I don't know, if this the best approach but it works fine for me atm.

Reply via email to