-
Couldn't load subscription status.
- Fork 90
Grok Various data structures
This page is a part of the Grokking Nemerle tutorial.
Tuples are forms of nameless data structures. They are usable when you need to return two or three values from a function.
A tuple is constructed with:
(expr1, expr2, ..., exprN)and deconstructed with:
def (id1, id2, ..., idN) = expr;This def thing defines values called id1 through idN
and puts respective tuple members into them.
Tuple types are written using the * operator. For example, pair
of integers (42, 314) has the type int * int, while
("Zephod", 42.0, 42) has the type string * double * int.
An example follows:
/** Parses time in HH:MM format. */
parse_time (time : string) : int * int
{
def arr = time.Split (array [':']);
(System.Int32.Parse (arr[0]), System.Int32.Parse (arr[1]))
}
seconds_since_midnight (time : string) : int
{
def (hours, minutes) = parse_time (time);
(hours * 60 + minutes) * 60
}
foo () : void
{
def secs = seconds_since_midnight ("17:42");
...
}Another example could be:
// split (3.7) => (3, 0.7)
split (x : double) : int * double
{
def floor = System.Math.Floor (x);
(System.Convert.ToInt32 (floor), x - floor)
}List literals are special forms of writing lists. Lists are data
structures that are used very often in Nemerle - often enough to get
their own syntax. Lists in Nemerle are somewhat different than the
ArrayList type in .NET.
- the lists in Nemerle are immutable (cannot be changed once created)
- items can be appended at the beginning only (constructing new lists)
ArrayList.
Anyway, to construct a list consisting of a given head (first
element) and a tail (rest of elements, also a list), write:
head :: tailTo construct a list with specified elements write:
[ element_1, element_2, ..., element_n ]This way you can also construct an empty list ([]).