3月31日,Nemerle发布了它的0.2.10版本。在这篇文章中,我们通过Nemerle的Tutorial来看看这种.net上的新语言。
Nemerle is a new functional language designed from the ground up for the .NET. In this paper we have focused on features absent in traditional ML-like and object-oriented languages: variant inheritance, assertions and powerful code-generating macros. We also gave concern for the syntax and the “spirit” of Nemerle that makes it a good transition language for programmers with C# background.
这是Nemerle的intro里对它的介绍,为了保证准确性,我们引用了全文。而它的一些特性我们通过下面的几个例子来概览Nemerle.
using System.Console;
public class Adder
{
public static Main () : void
{
WriteLine ("The sum is {0}",
Int32.Parse (ReadLine ()) +
Int32.Parse (ReadLine ()));
}
}
这个程序实现了输入两个数并输出他们的和。从这段代码里,我们可以清晰的看到void等返回类型都写到了右边的冒号后面,而且在使用using的时候,引用的不单单是命名空间(namespace),还可以引用类的成员了,这样使得我们的WriteLine()和ReadLine()函数都可以直接的使用。
我们换一种方式来实现
public class Adder
{
// It is private by default.
static ReadInteger () : int
{
Int32.Parse (Console.ReadLine ())
}
public static Main () : void
{
def x = ReadInteger (); // Variable definition.
def y = ReadInteger ();
// Use standard .NET function for formatting output.
Console.WriteLine ("{0} + {1} = {2}", x, y, x + y);
}
}
事实上我们更希望使用这种方法来实现我们的目的。在Main()函数里我们
定义了两个值x和y,是通过def关键字实现的,您也看到了我们并没有写出
变量究竟是什么类型的,编译器看到ReadInteger返回int型后就把x定义
为int型变量了。我们称之为类型推断(Type Inference)
{
public static Main () : void
{
// Open a file.
def sr = System.IO.StreamReader ("SomeFile.txt"); // (1)
mutable line_no = 0; // (2)
mutable line = sr.ReadLine ();
while (line != null) { // (3)
System.Console.WriteLine (line);
line_no = line_no + 1; // (4)
line = sr.ReadLine ();
}; // (5)
System.Console.WriteLine ("Line count: {0}", line_no);
}
}
{
public static Main () : void
{
def sr = System.IO.StreamReader ("SomeFile.txt");
mutable line_no = 0;
def read_lines () : void { // (1)
def line = sr.ReadLine ();
when (line != null) { // (2)
System.Console.WriteLine (line); // (3)
line_no = line_no + 1; // (4)
read_lines () // (5)
}
};
read_lines (); // (6)
System.Console.WriteLine ("Line count: {0}", line_no); // (7)
}
}
{
public static Main () : void
{
def sr = System.IO.StreamReader ("SomeFile.txt");
def read_lines (line_no : int) : int { // (1)
def line = sr.ReadLine ();
if (line == null) // (2)
line_no // (3)
else {
System.Console.WriteLine (line); // (4)
read_lines (line_no + 1) // (5)
}
};
System.Console.WriteLine ("Line count: {0}", read_lines (0)); // (6)
}
}
这段程序从(3)处结束并返回结果,而参数的累加结果正是最后输出的line_no的值.