5 Built-in functions, classes, methods, and constants
5.1 Primitive classes
DSSL2 includes seven primitive classes for building up more complex data structures. The constructors and methods of these classes are documented in this subsection.
5.1.1 Class bool
The primitive class for Boolean values, True and False. The type predicate for class bool is bool?.
Booleans support logical binary operators & (and), \| (or, written without the backslash), and ^ (xor), and logical unary negation ~. They also support comparison with ==, <, <=, etc. False compares less than True.
procedure
bool() -> bool?
The constructor for class bool.
In its one-argument form, converts any type to bool. All values but False and None convert to True.
In its no-argument form, returns False.
5.1.2 Class char
The primitive class for representing a single character of text. The type predicate for class char is char?.
A character can be converted to its integer value with the int constructor. Characters can be compared with ==, <, <=, etc.
procedure
char() -> bool?
The constructor for class char.
Given a character, returns that character. Given an integer, returns the character corresponding to the Unicode code point, or errors if the integer is not a valid Unicode character. Given a one-character string, returns the character of the string; any longer or shorter string is an error.
5.1.3 Class int
The primitive class for representing integral quantities of unlimited size. The type predicate for class int is int?.
Integers support binary arithmethic operators + (addition), - (subtraction), * (multiplication), and / (integer division); when combined with an instance of class float, the result will also be a float. They also support unary + (identity) and - (negation).
They also support comparison with ==, <, <=, etc., and they can be compared against floats.
Integers support binary bitwise operators & (bitwise and), \| (bitwise or), and ^ (bitwise xor), and unary bitwise negation ~.
procedure
int() -> int?
The constructor for class int.
Given a number, returns the integer part, by truncation. That is, the decimal point and everything after it is removed.
Given a character, returns the Unicode code point value.
Given a string, attempts to convert to a number before truncating, throwing an error if the conversion fails.
Booleans True and False convert to 1 and 0, respectively.
Given no arguments, returns 0.
method
Returns the absolute value of the receiving integer.
method
«int».ceiling() -> int?
Returns the same integer.
method
«int».floor() -> int?
Returns the same integer.
method
«int».sqrt() -> float?
Returns the square root of the receiving integer, as a float.
method
The cosine function.
method
The sine function.
method
The tangent function.
method
«int».acos() -> float?
The inverse cosine function.
method
«int».asin() -> float?
The inverse sine function.
method
«int».atan() -> float?
The inverse tangent function.
Optionally takes an argument, in which case y.atan(x) computes the angle from the origin to the Cartesian point (x, y).
5.1.4 Class float
The primitive class for representing approximations of real numbers (as 64-bit IEEE 754 numbers). The type predicate for class float is float?.
Floats support binary arithmethic operators + (addition), - (subtraction), * (multiplication), and / (division); when combined with an instance of class int, the result will also be a float. They also support unary + (identity) and - (negation).
They also support comparison with ==, <, <=, etc., and they can be compared against ints.
procedure
float() -> float?
The constructor for class float.
Converts an exact integer to the nearest double-precision floating point value. If given a string, attempt to convert to a number, throwing an error if the conversion fails. Booleans True and False convert to 1.0 and 0.0, respectively.
Given no arguments, returns 0.0.
method
«float».abs() -> float?
Returns the absolute value of the receiving float.
method
«float».ceiling() -> int?
Returns smallest integer that is no less than the receiving float. That is, it rounds up to the nearest integer.
method
«float».floor() -> int?
Returns the largest integer that is no greater than the receiving float. That is, it rounds down to the nearest integer.
method
«float».sqrt() -> float?
Returns the square root of the receiving float.
method
«float».cos() -> float?
The cosine function.
method
«float».sin() -> float?
The sine function.
method
«float».tan() -> float?
The tangent function.
method
«float».acos() -> float?
The inverse cosine function.
method
«float».asin() -> float?
The inverse sine function.
method
«float».atan() -> float?
The inverse tangent function.
Optionally takes an argument, in which case y.atan(x) computes the angle from the origin to the Cartesian point (x, y).
5.1.5 Class proc
The primitive class for representing functions. The type predicate for class proc is proc?.
Procedures can be applied.
procedure
proc() -> proc?
The constructor for class proc.
Given one procedure argument, returns it unchanged. Given no arguments, returns the identity function.
method
«proc».compose(proc?) -> proc?
Composes the receiving procedure with the parameter procedure. For example,
assert (λ x: x + 1).compose(λ x: x * 2)(5) == 11
method
«proc».vec_apply(vec?) -> AnyC
Applies the receiving procedure using the contents of the given vector as its arguments.
5.1.6 Class str
The primitive class for representing textual data. The type predicate for class str is str?.
A string can be indexed with square bracket notation, which returns an instance of class char. Strings may be concatenated with the + operator. Concatenating a string with a non-string using + converts the non-string to a string first.
procedure
str() -> str?
The constructor for class str.
Given one string argument, returns that argument unchanged.
Given one non-string argument, converts that argument to a string according to the %p format specifier.
Given two arguments, a natural len and a character c, makes a string of the given length len, repeating character c.
Given no arguments, returns the empty string.
method
«str».explode() -> VecC[char?]
Breaks the receiving string into a vector of its characters.
method
«str».format(AnyC, ...) -> str?
Formats the given arguments, treating the receiving string as a format string in the style of print.
For example,
assert '%s or %p'.format('this', 'that') == "this or 'that'"
method
Returns the length of the receiving string in characters.
5.1.7 Class vec
The primitive vector class, for representing sequence of values of fixed size. The type predicate for class vec is vec?.
A vector can be indexed and assigned with square bracket notation.
procedure
The constructor for class vec.
Given no arguments, returns an empty, zero-length vector.
Given one argument, returns a vector of the given size, filled with None.
Given two arguments, returns a vector of the given size, with each element initialized by applying the given function to its index. That is, vec(len, init) is equivalent to [ init(i) for i in len ].
method
«vec».filter(pred?: FunC[AnyC, AnyC]) -> vec?
Filters the given vector, by returning a vector of only the elements satisfying the given predicate pred?.
In particular, v.filter(pred?) is equivalent to [ x for x in v if pred?(x) ]
method
«vec».implode() -> vec?
If the receiver is a vector of characters, joins them into a string. (Otherwise, an error is reported.)
method
Returns the length of the vector.
method
Maps a function over a vector, returning a new vector.
In particular, v.map(f) is equivalent to [ f(x) for x in v ]
5.2 Predicates
5.2.1 Basic type predicates
procedure
Determines whether its argument is a Boolean, that is an instance of class bool.
procedure
Determines whether its argument is an instance of class char.
procedure
Determines whether its argument is a contract. Contracts include many constants (numbers, strings, Booleans), single-argument functions (considered as predicates), and the results of contract combinators such as OrC and FunC.
See Contracts for more.
procedure
flat_contract?(AnyC) -> bool?
Determines whether its argument is a flat contract. Flat contracts are contracts that answer right away and return the protected value unchanged on success, rather than wrapping it. Flat contracts include constants (numbers, strings, Booleans), single-argument functions, and the results of contract combinators such as OrC and AndC applied to flat contracts. Non-flat contracts include the results of FunC and VecC.
See Contracts for more.
procedure
Determines whether its argument is an instance of class int.
procedure
Determines whether its argument is an instance of class float.
procedure
Determines whether its argument is an instance of class proc.
procedure
Determines whether its argument is an instance of class str.
procedure
Determines whether its argument is an instance of class vec.
5.2.2 Numeric predicates
procedure
Determines whether its argument is a number. This includes both class int and class float.
procedure
Determines whether its argument is a non-negative integer.
procedure
Determines whether its argument is a number equal to zero.
procedure
Determines whether its argument is a number greater than zero.
procedure
Determines whether its argument is a number less than zero.
procedure
Determines whether its argument is an even number.
procedure
Determines whether its argument is an odd number.
procedure
Determines whether its argument is the special class float not-a-number value. This is useful, since nan is not necessarily == to other instances of nan.
5.3 Comparison operations
procedure
Compares two values of any type. If the values are incomparable, returns None. Otherwise, returns an integer: less than 0 if the first argument is less, 0 if equal, or greater than 0 if the first argument is greater.
procedure
Returns the largest of the given arguments, using cmp to determine ordering. It is an error if the values are not comparable.
procedure
Returns the smallest of the given arguments, using cmp to determine ordering. It is an error if the values are not comparable.
5.4 Randomness operations
procedure
When called with zero arguments, returns a random floating point number in the open interval (0.0, 1.0).
When called with one argument limit, returns a random integer from the closed interval [0, limit - 1].
When called with two arguments start and limit, returns a random integer from the closed interval [start, limit - 1]. The difference between the arguments can be no greater than 4294967087.
constant
Defined to be 4294967087, the largest parameter (or span) that can be passed to random.
procedure
random_bits(nat?) -> nat?
Returns a natural number consisting of the requested number of random bits. That is, given n, returns an integer in the closed interval [0, 2 ** n - 1]. This procedure may be slow, but it is not limited by RAND_MAX in the way that the random procedure is.
5.5 I/O Functions
procedure
The first argument is treated as a format string into which the remaining arguments are interpolated, and then the result is printed.
The format string is a string that contains a formatting code for each additional argument, as follows:
%p – prints the object, formatted nicely if possible
%d – prints the object in raw, debug mode, ignoring user-defined printers
%s – interpolates a string or character as itself, without quoting; the same as %p for other types
For example:
let a = 3 let b = 4 print("%p + %p = %p", a, b, a + b)
prints “3 + 4 = 7”.
procedure
If the first argument is a string then println is like print, but adds a newline at the end.
If the first argument is a non-string or there are no arguments, then println prints all the arguments with commas in between and a newline after, as if formatted by "%p, …, %p\n".
If DSSL2 supported user-defined varargs functions, it might be defined as:
def println(*args): |
if args.len() == 0: |
print('\n') |
elif str?(args[0]): |
print(*args) |
print('\n') |
else: |
let fmt = '' |
for _ in args: |
fmt = '%p' if fmt == '' else fmt + ', %p' |
println(fmt, *args) |
procedure
current_directory() -> str?
Given with no arguments, current_directory returns the current working directory as a string.
Called with one string argument s, current_directory attempts to change the working directory to the directory named by s. It is an error if the directory does not exist or the operation isn’t permitted.
procedure
file_to_string(str?) -> str?
Given the name of a file, reads its entire contents and returns it as a string.
It is an error if the file doesn’t exist or cannot be read.
procedure
string_to_file(message: str?, filename: str?) -> NoneC
Writes string message to file filename. If the file doesn’t exist, it is created; if it already exists then its contents are replaced.
It is an error if the file cannot be written.
5.6 Other functions
procedure
Terminates the program with an error message.
If a first argument is supplied and it is a string, then the error message will be produced by interpolating the remaining arguments into the string à la print.
If there are no arguments, or if the first argument is not a string, then it formats all the arguments with commas in between and a “call” to error around it. This ensure that all calls to error produce some kind of sensible output.
procedure
Equivalent to o.len().
procedure
Given an object, returns a vector of the names of its methods. Given a struct, returns a vector of the names of its fields.