-
Notifications
You must be signed in to change notification settings - Fork 89
Common code patterns tutorial
We will write some example code, so you can see some common code patterns when writing programs in Nemerle.
Let us create an array and print its elements walking through it in loop.
using System.Console;
module MyApp
{
Main () : void
{
// create an array containing strings (array [string])
def elements = array ["{0}", "a {0} a", "{0}", "b {0}", "b {0}"];
// iterate through elements of array
for (mutable i = 0; i < elements.Length; i++)
// print current value of `i' with using format from array
WriteLine (elements [i], i);
}
}
The keys stored in elements array looks a little bit strange, but we will use WriteLine method as a good example of processing key together with value associated to it.
We will now make the collection of keys unique. For this purpose we will use generic dictionary type, which in Nemerle is called Nemerle.Collections.Hashtable.
using Nemerle.Collections;
using System.Console;
module MyApp
{
Main () : void
{
// create an array containing strings (array [string])
def elements = array ["{0}", "a {0} a", "{0}", "b {0}", "b {0}"];
def hash = Hashtable ();
// count the number of occurrences of each unique element
foreach (e in elements)
{
unless (hash.Contains (e))
hash[e] = 0;
hash[e] += 1;
}
// print each element with number indicating its total count
foreach (keypair in hash) {
WriteLine (keypair.Key, keypair.Value);
}
}
}
For each entry in hashtable we store the number of how many times it occured.
Ok, iterating over collection with foreach is nice, but it is still *too long*!
// print each element with number indicating its total count
foreach (keypair in hash)
WriteLine (keypair.Key, keypair.Value);
// pass matching overload of WriteLine to iteration method
hash.Iter (WriteLine)
Hashtable have the special Iter overload, which takes a generic two-argument function, which will be called for every element stored in collection. The declaration of Iter looks like this:
class Hashtable ['a, 'b]
{
public Iter (f : 'a * 'b -> void) : void
{ ... }
...
}
and after substituting 'a and 'b with actual types in our hash, we just use
it as Iter : (string * int -> void) -> void
, which takes string * int -> void
function as
the only argument.
And one more way of iterating over a Hashtable is to query KeyValuePairs property and use pairs of key and value in foreach statement:
foreach( (key, value) in hash.KeyValuePairs)
WriteLine(key, value);