Nemerle Lectures

1. Classes and modules

class Foo 
{ 
  // ... 
}
module Bar
{
  // ... 
}

1.1. Methods

module Foo
{
  public SomeMethod () : void
  {
    // ...
  }
  private SomeOtherMethod (x : int) : int
  {
    // ... 
  }
  private Frobnicate (x : int, y : string) : int
  {
    // ... 
  }
}

1.2. Fields

module Bar
{
  qux : int;
  private quxx : int;
  bar : float;
}

2. Expressions

module Hello
{
  Main () : void
  {
    System.Console.WriteLine ("Hello cruel world!")
  }
}

if

fib (n : int) : int
{
  if (n < 2)
    1
  else
    fib (n - 1) + fib (n - 2)
}

local function, type inference, failure with it

fib (n : int) : int
{
  def loop (last1 : int, last2, cur) {
    if (cur >= n)
      last2
    else
      loop (last2, last1 + last2, cur + 1)
  };
  loop (1, 1, 1)
}

semicolon after for, mutable, def, assignment

fib (n : int) : int
{
  mutable last1 <- 1;
  mutable last2 <- 1;
  
  for (mutable cur <- 1; cur < n; cur <- cur + 1) {
    def tmp = last1 + last2;
    last1 <- last2;
    last2 <- tmp;
  };

  last2
}

using framework classes, no new, printf, what the heck?

the_answer_to_the_universe () : int
{
  def r = System.Random ();
  r.Next (100)
}

print_answer () : void
{
  def the_answer = the_answer_to_the_universe ();
  System.Console.WriteLine ("The answer to the Ultimate " +
                            "Question of Life, the " +
                            "Universe and Everything " +
                            "is {0}", the_answer)
}

printf_answer () : void
{
  def the_answer = the_answer_to_the_universe ();
  printf ("The answer is %d\n", the_answer);
}

array type syntax, when, assignment again, type enforcement, array ctor syntax

module M {
  reverse_array (ar : array <int>) : void
  {
    def loop (left, right) {
      when ((left : int) < right) {
        def tmp = ar[left];
        ar[left] <- ar[right];
        ar[right] <- tmp;
        loop (left + 1, right - 1)
      }
    };
    loop (0, ar.Length - 1)
  }

  print_array (ar : array <int>) : void
  {
    for (mutable i <- 0; i < ar.Length; i <- i + 1)
      printf ("%d\n", ar[i])
  }

  Main () : void
  {
    def ar = array [1, 42, 3];
    print_array (ar);
    printf ("\n");
    reverse_array (ar);
    print_array (ar);
  }
}

3. Exercises

3.1. List 1

1. Write a program that prints out to the console:

1 bottle of beer.
2 bottles of beer.
3 bottles of beer.
...
99 bottles of beer.

With appropriate amount of beer instead of .... Program source code shouldn't exceed 30 lines.

2. Implement bogo sort algorithm for array of integers. (WARNING: you should not implement ,,destroy the universe'' step). Test it by sorting the following array: [4242, 42, -42, 31415].

4. Class library reference

Class library reference from Microsoft can be found under http://msdn.microsoft.com/library/en-us/cpref/html/cpref_start.asp.