Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Common code patterns tutorial

jellicle edited this pageAug 8, 2011 ·1 revision

We will write some example code, so you can see some common code patterns when writing programs in Nemerle.

Small app with array and Hashtable

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.

Counting unique elements

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.

What about functional programming?

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);

Clone this wiki locally


[8]ページ先頭

©2009-2025 Movatter.jp