- Notifications
You must be signed in to change notification settings - Fork91
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 arrayfor (mutable i =0; i < elements.Length; i++)// print current value of `i' with using format from array WriteLine (elements [i], i); }}
The keys stored inelements array looks a little bit strange, but we will useWriteLine 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 calledNemerle.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 elementforeach (ein elements) {unless (hash.Contains (e)) hash[e] =0; hash[e]+=1; }// print each element with number indicating its total countforeach (keypairin 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 withforeach is nice, but it is still *too long*!
// print each element with number indicating its total countforeach (keypairin hash) WriteLine (keypair.Key, keypair.Value);// pass matching overload of WriteLine to iteration methodhash.Iter (WriteLine)
Hashtable have the specialIter overload, which takes a generic two-argument function, which will be called for every element stored in collection. The declaration ofIter looks like this:
class Hashtable ['a,'b] {public Iter (f :'a *'b->void) :void { ... }...}
and after substituting 'a and 'b with actual types in ourhash, we just use it asIter : (string * int -> void) -> void, which takesstring * int -> void function as the only argument.
And one more way of iterating over a Hashtable is to queryKeyValuePairs property and use pairs of key and value inforeach statement:
foreach( (key, value)in hash.KeyValuePairs) WriteLine(key, value);