Next: , Previous: Variables declaration, Up: Translating C into L


2.1.1.2 Type declaration and utilisation

Type declaration (typedef in C) are written as follows:

     type Toto = struct { Int foo; Int baz;};

L's convention for types is that they should be capitalized, and if you have an identifiers that spans over several words, separate them by underscores and capitalize each word, Like_That.

But this is is really just a convention; your own program can be written as you like.

The type = declaration isn't like typedef, because it introduces a new type that is incompatible with the first. (COMMENT : the = is maybe misleading in that case?)

If you write, for instance:

     type Kelvin = Float;

then you cannot have:

     let Kelvin k = 3.0;

You have to do this instead: (UNIMPLEMENTED: does not work for now, explicit casts needed)

     let Kelvin k = Kelvin(3.0);

or simply:

     let k = Kelvin(3.0);

Similarly, the + operations work on Ints, and because Kelvins are not Ints, you cannot add Kelvins.

L provides a shortcut (UNIMPLEMENTED) for specifying which operations are still allowed for the new type:

     type Kelvin = Float | allows +,-;

Forbiding * is interesting for instance, because multiplying Kelvins between them make no sense. Multiplying them by a Float makes sense, however. (UNIMPLEMENTED: so we need a way to tell that).

Finally, writing all this can be factorized to:

     import std.unit;
     
     type Kelvin = Float : unit;

unit declares a type that does all this (in fact, that respects the unit interface). numeric declares a type that has +, -, *, /. All these are in fact type classes, see Type classes.

If you just want something similar to C typedef, you can use L's typealias:

     typealias Floating_Point = Float;
     typealias Integer = Int;

defines Integer as an alias for Int. (i.e. they are the same type with just different names.)