Type & Specification Directives
Type and specification directives start with at (@)
.
Types annotations help you build robust systems with confidence. Statically typed languages can be expressive, only if they don't force you to add type annotation when value types are obvious.
In U, types are not required unless U compiler needs more hints on your intent. You do not have to write type information down everywhere. The compiler automatically figures out most types. This can make the code easier to read and maintain.
All types are guarded by the '@'
aperture.
:a : @int32 3 # 'a' is an Int32, initialized to 3
:size_t : @{long;unsigned;int;} # 'size_t' has C-type 'long unsigned int'
There are two type annotation kind:
- builtin types: starts with
@
, - user defined types: starts with
@
.
Type annotations are right associatives.
Unit Type¶
When an expression may does not return a value, the unit type @
is returned. For example, expressions that print on host, does not return a value, they just send data to host. Therefore, unit type is returned:
Options¶
U has no concept of null
. When an expression may not return a value, options let you easily return an optional type.
For example:
:divide : {: a, b
:? a == 0, ::none, ::some a / b
}
# <divide> return an option type
result : divide 1, 0
:? result, {
# Valid division
:- ::some(x), \< "Result: \:x"
# Inalid division
:- ::none, \< "Cannot divide by 0"
}
You can use @?
instead of ::some
.
Specification¶
To build reliable systems, some domains requires more controls and need specification annotations or specs. Usually they relate to the Design by Contract approach:
- Pre, Post conditions
- Side effects
- Invariants
- ...
As types and specifications share the same goal: building robust systems, they are grouped under the same aperture.
Instead of building this approach into U, specs are available user defined function; but are accessible with the aperture @!
. Like the error aperture :!
, the aperture @!
reminds you that U will raise an error if a specification is not guaranteed.
@:even : {: n
@!? n % 2 == 0, '\:n is Not an even number'
# Or
@!? {
:- n.@?number, '\:n is not a number'
:- n % 2 == 0, '\:n is not an even number'
}
}
:a : 5
:e : @!even a
# Raise an error
The aperture @!?
assert specifications.
Generics¶
Work in progress...
Generalized Algebraic Data Types¶
Work in progress...