Quick Guide

This is a small guide to nearly all Nemerle features, specially for people coming from C#:

Contents

Variables

In all variables, type inference works

Lists

List comprehensions

more...

Useful methods on lists

Arrays

Tuples

Nemerle.Utility.Pair

This class contains three methods that work with pairs (tuples of two elements):

Decisions

Loops

Exceptions

try {
  code
}
catch {
  | e is ArgumentNullException => ...
  | e is OverflowException => ...
  | _ => ...
}
finally {
  // Finally code is always executed
  // no matter an exception where thrown or not
}

Variants

variant Volume {
  | Max
  | Min
  | Other { v : int }
}

Enums

As in C#, are just a good face for ints:

enum Seasons {
  | Spring
  | Autumn
  | Winter
  | Summer
}

Pattern Matching

Literal matching

match (value) {
  | 1 => "one"
  | 2 => "two"
  | _ => "more"
}
match (value) {
  | "one" => 1
  | "two" => 2
  | _ => 0
}
match (value) {
  | Seasons.Spring
  | Seasons.Summer => "hot"
  | _ => "cold"
}

List matching

match (some_list) {
  | [42, 42] => "two forty-two"
  | [42, _] => "forty-two on first position of two-element list"
  | [_, 42] => "forty-two on second position of two-element list"
  | 42 :: _ => "forty-two on first position"
  | _ :: 42 :: _ => "forty-two on second position"
  | [] => "an empty list!"
  | _ => "another list"
}

Variable pattern

Binds the variable names:

def display (l) {
  match (l) {
    | head :: tail =>
      Write ($ "$head, ");
      display (tail)
    | [] =>
      WriteLine ("end")
  }
}

Tuple pattern

match (tuple) {
  | ( 42, _ ) => "42 on first position"
  | ( _, 42 ) => "42 on second position"
  | ( x, y ) => $"( $x, $y )"
}

Type check

Checks if the value is of given type, binding the new value with the new type

def check (o : object) {
  match (o) {
    | i is int => $"An int: $i"
    | s is string => $"A string: $(s.ToUpper())"
    | _ => "Object of another type"
  }
}

Record pattern

Binds on field or properties

def check_class (c) {
  match (c) {
    | MyClass where (foo = 0) => true
    | _ => false
  }
}

If the type is known to the compiler, the where clause is not needed

def check_class (c) {
  match (c) {
    | (foo = 0) => true
    | _ => false
  }
}

as pattern

Binds a value matched with an identifier

variant Foo {
  | A { x : int; mutable y : string; }
  | B
}
 
match (some_foo ()) {
  | A (3, _) as a =>
    a.y = "three";
  | _ => {}
}

Type hint pattern

Used to explicitly declare types where the compiler cannot infer it

def foo (l) {
  | (s : string) :: _ => s [0]
  | [] => '?'
}

with clase

Used to specify a default value in cases where we need to match both a small and a big structure with the same code.

def foo (_) {
  | [x] with y = 3
  | [x, y] => x * y
  | _ => 42
}

Regular Expressions match

regexp match (str) {
  | "a+.*" => printf ("a\n");
  | @"(?<num : int>\d+)-\w+" => printf ("%d\n", num + 3);
  | "(?<name>(Ala|Kasia))? ma kota" =>
     match (name) {
       | Some (n) => printf ("%s\n", n)
       | None => printf ("noname?\n")
     }
  | _ => printf ("default\n");
}

you must add a reference to Nemerle.Text to use this functionality (using Nemerle.Text)

Yield

Range (from : int, to : int) : IEnumerable[int] {
  for (mutable i = from; i <= to; i++)
    yield i;
}

Imperative programming and Blocks

To use return, break and continue we need to open the Nemerle.Imperative namespace:

Blocks are a set of instructions, preceded with an identifier and a colon. The result of the block is the last value computed, except if the name of the block is used,along with the return value, to jump out the block.

def x =
  foo: {
    when (some_cond) foo (3); // if some_cond is true, the block will return 
    qux ();
    42 // else it will return 42
  }

more...

Functions

public Greet (people : list[string]) : void {
  def say_hello (s) {
    System.Console.WriteLine ($"Hello $s");
  }
 
  foreach (person in people)
    say_hello (person);
}

String formatting

print Functions

Type conversions

Namespaces

Classes and Modules

Interfaces

Defines a set of public methods an adhering class must implement

interface IExample {
  Method() : void;
}
 
class Example : IExample {
  public Method () : void { ... }
}

Accessibility

Modifiers

Constructors

class Example {
  mutable Name : string;
  public this (name : string) {
    Name = name;
  }
}

Static Constructors

Executed once per type. No parameters.

class Example {
  static public this() { ... }
}

[Record] macro

Generates a constructor wich assigns a value to every field:

[Record] class Point {
  public x : int; public y : int;
}

is the same as:

class Point {
  public x : int; public y : int;
  public this (x : int, y : int) {
    this.x = x; this.y = y
  }
}

Inheritance

Modifiers

Parameters

Properties

public Property : string {
  get { property }
  set { property = value }
}

Property Accessors

more...

Flag Accessors

For setting individual bits of enumerations fields, making boolean propeties:

[System.Flags] enum States {
  | Working = 0x0001
  | Married = 0x0002
  | Graduate = 0x0004
}
 
[FlagAccessor (Working, Married, Graduate, flags=WantSetter)]
mutable state : States;

Indexers

class Table {
  public Item [row : int, column : int] {
    get { ... }
    set { ... }
  }
}

Operator Overloading

[Record]
class Vector {
  [Accessor] x : double;
  [Accessor] y : double;
  [Accessor] z : double;
 
  public static @+ (v1 : Vector, v2 : Vector) : Vector {
    Vector (v1.X + v2.X, v1.Y + v2.Y, v1.Z + v2.Z)
  }
}

Delegates and Events

Genericity

class Example[T] {
  mutable item : T
}

Constraints

Design by contract

All types needed are included in the Nemerle.Assertions namespace. By default, if contract is violated a Nemerle.AssertionException is thrown. You can change it by means of otherwise

getfoo (i : int) : int
requires i >= 0 && i < 5 otherwise throw
  System.ArgumentOutOfRangeException ()
{ ... }

Preconditions

class String 
{
  public Substring (startIdx : int) : string 
  requires startIdx >= 0 && startIdx <= this.Length
  { ... }
}
ConnectTrees (requires (!tree1.Cyclic ()) tree1 : Graph,
              requires (!tree2.Cyclic ()) tree2 : Graph, 
              e : Edge) : Graph 
{ ... }

Postconditions

public Clear () : void
ensures this.IsEmpty
{ ... }

Class invariants

class Vector [T]
invariant position >= 0 && position <= arr.Length
{ ... }
expose (this) {
  x += 3;
  y += 3;
}

more...

Lazy evaluation

class InfList {
  public Val : int;
  public Next : LazyValue [InfList];
 
  public this (v : int) {
    Val = v;
    Next = lazy (InfList (v + 1)); 
  }
}

more...

Type aliases

Operators

Logical Operators

You can also use and, or, not if you open the Nemerle.English namespace

Bit Operators

Checked and unchecked contexts

Some things inherited from C# =

Logging

All macros are inside the Nemerle.Logging namespace:

more...

Assertions

SQL macros

ExecuteReaderLoop ("SELECT * FROM employee WHERE firstname = $myparm",
dbcon, 
{
  Nemerle.IO.printf ("Name: %s %s\n", firstname, lastname)
});

more...

Concurrency macros

All this macros are in Nemerle.Concurrency namespace

Chords

Chords are sets of methods that only return a value when some exact amount of them are called in some order. This example states very well both the syntax and uses of chords:

class Buffer [T]
{
    [ChordMember]
    public Put (msg : T) : void;
 
    public Get () : T
    chord {
      | Put => msg
    }
}

More examples can be found at the SVN repository

Nemerle Standard Library

Collection classes

All in Nemerle.Collections namespace:

Array and String extensions

This methods live in Nemerle.Utility namespace, in NArray and NString classes, but can be used in arrays and string in code in a normal way. The methods adds functionality à la list for these two types.

Nemerle.IO

Contains helper functions for handling an input stream: ReadIntDigits, ReadRealDigits, ReadString, ReadChat, ConsumeWhiteSpace and CheckInput.

Option

The type option['a] allows to save values that can be null. option.None tells that it has no value. option.Some (value) saves a value.