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), // (integer division), and / (float division, which always produces a class 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 ~.
Integer operations require O(1) time.
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.
Do note that, to take the square root of a literal integer, it must be in parentheses:
(2).sqrt()
Without parentheses, the parser (lexer, really) expects to see a float when it sees the dot.
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).
method
The logarithm function.
Without an argument, returns the natural logarithm of the receiver. When an argument, returns the logarithm of the receiver using the argument as the base.
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.
Float operations require O(1) time.
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).
method
«float».log() -> float?
The logarithm function.
Without an argument, returns the natural logarithm of the receiver. When an argument, returns the logarithm of the receiver using the argument as the base.
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
Returns the length of the receiving string in characters.
O(1) time and space.
method
«str».explode() -> VecC[char?]
Breaks the receiving string into a vector of its characters.
O(n) time and space.
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'"
5.1.7 Class vec
The primitive vector class, for representing sequence of values of fixed size.
This section documents only the methods of the vector class. Vector-specific syntax (i.e., square brackets for indexing and construction) is documented with the other expression syntax.
The type predicate for class vec is vec?.
procedure
The constructor for class vec.
Given no arguments, returns an empty, zero-length vector.
Given one argument, returns a vector of size n, 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(n, init) is equivalent to [ init(i) for i in range(n) ].
method
Returns the length of the vector.
O(1) time and space.
method
Returns the element at index i. Equivalent to v[i]
O(1) time and space.
method
Replaces the element at index i in the vector with new. Equivalent to v[i] = new
O(1) time and space.
method
«vec».mem?(i: nat?) -> bool?
Returns whether i is a valid index into the vector. Equivalent to 0 <= i and i < v.len()
O(1) time and space.
method
«vec».implode() -> vec?
If the receiver is a vector of characters, joins them into a string. (Otherwise, an error is reported.)
O(n) time and space.
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 ]
O(n × Tf) time and O(n + Sf) space.
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) ]
O(n × Tpred?) time and O(n + Spred?) space.
5.1.8 Class range_iterator
An iterator over a range of numbers, constructed by range.
5.2 Predicates
All the predicates below require O(1) time.
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.
procedure
range_iterator?(AnyC) -> bool?
Determines whether its argument is an instance of class range_iterator.
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 natural number. Natural numbers include zero.
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
All the comparisons below require O(1) time.
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 two given arguments, using cmp to determine ordering. It is an error if the values are not comparable.
procedure
Returns the smallest of the two 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
%% – prints a literal "%" sign
For example:
let a = 3 let b = 4 print("%p + %p = %p", a, b, a + b)
prints “3 + 4 = 7”.
procedure
Like print, but adds a newline after its output.
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
range(start: num?, limit: num?, step: num?) -> range_iterator?
range(start: num?, limit: num?) -> range_iterator?
range(limit: num?) -> range_iterator?
Returns an iterator over the closed-open interval from start to stop in increments of step.
For example, range(0, 10, 2) counts upward from 0 to 10 by 2s, producing five values:
assert [ n for n in range(0, 10, 2) ] == [ 0, 2, 4, 6, 8 ]
Whereas range(50, 0, -15) counts downward from 50 to 0 by 15s, producing four values:
assert [ n for n in range(50, 0, -15) ] == [ 50, 35, 20, 5 ]
If two arguments are given then they are the start and the limit, and if only one argument is given then it’s the limit. In the two- and one-argument forms the step defaults to 1. In the one-argument form, the start defaults to 0. For example:
assert [ n for n in range(3, 7) ] == [ 3, 4, 5, 6 ] assert [ n for n in range(7, 3) ] == [] assert [ n for n in range(7) ] == [ 0, 1, 2, 3, 4, 5, 6 ]
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.