Elan Library Reference
Table of contents
Main topics | Detailed topics
Value data types
Integer
An integer is a whole number, i.e. one that has no fractional part. It may be represented in decimal, hexadecimal or binary:
100100100100100 (decimal), 0x640x640x64&H640x64 (hexadecimal) and 0b11001000b11001000b1100100&B11001000b1100100 (binary) all have the same value.
Its type is IntintintIntegerint.
name of type |
examples of defining a literal value |
IntintintIntegerint |
+constant maxNumbername? set to 10literal value or data structure?0+maxNumbername? = 10literal value or data structure? # constant1+const Int maxNumbername? = 10literal value or data structure?;2+Const maxNumbername? = 10literal value or data structure?3+static final Int maxNumbername? = 10literal value or data structure?; // constant4 |
IntintintIntegerint |
variable flagsname? set to 0b1100100value or expression?5flagsname? = 0b1100100value or expression? # variable definition6var flagsname? = 0b1100100value or expression?;7Dim flagsname? = &B1100100value or expression? ' variable definition8var flagsname? = 0b1100100value or expression?;9 |
Function dot methods on an IntintintIntegerint
function dot method |
argument types |
return type |
returns |
| asBinary |
(none) |
StringstrstringStringString |
string of binary digits representing the argument's integer value |
| equals |
IntintintIntegerint |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if integer and argument values are equal – falseFalsefalseFalsefalse otherwise |
| notEqualTo |
IntintintIntegerint |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if integer and argument values are unequal – falseFalsefalseFalsefalse otherwise |
| toString |
(none) |
StringstrstringStringString |
a string of decimal digits representing the argument's integer value |
Notes
- A literal integer or a named value of type
IntintintIntegerint may
always be passed into a function or procedure that is expecting a FloatfloatdoubleDoubledouble.
- The
IntintintIntegerint type is intended to represent whole numbers
in the range:
- Maximum: 253 − 1 (which is 9,007,199,254,740,991)
- Minimum value: −(253 − 1)
- If you go greater than the limit given above, the number will be accurate to approximately 17 decimal digits.
Larger numbers will be rounded with zeros at the end, unless they are larger than around 270, when they will automatically be shown
in exponential (scientific) format, as shown in the example.
Example of base conversion
● Functions to return an integer value as a hexadecimal string:
+function hexname?(n as Intparameter definitions?) returns StringType?
1
variable hname? set to ""value or expression?2
+if (n < 1)condition? then
3
assign hvariableName? to "0"value or expression?4
else5
variable mname? set to nvalue or expression?6
+while m > 0condition?
7
assign hvariableName? to hexDigit(m mod 16) + hvalue or expression?8
assign mvariableName? to divAsInt(m, 16)value or expression?9
end while
end if
return hvalue or expression?10
end function
+function hexDigitname?(i as Intparameter definitions?) returns StringType?
11
return "0123456789abcdef".subString(i, i + 1)value or expression?12
end function
+def hexname?(n: intparameter definitions?) -> strType?:
# function1
hname? = ""value or expression? # variable definition2
+if (n < 1)condition?:
3
hvariableName? = "0"value or expression? # assignment4
else:5
mname? = nvalue or expression? # variable definition6
+while m > 0condition?:
7
hvariableName? = hexDigit(m % 16) + hvalue or expression? # assignment8
mvariableName? = divAsInt(m, 16)value or expression? # assignment9
# end while
# end if
return hvalue or expression?10
# end function
+def hexDigitname?(i: intparameter definitions?) -> strType?:
# function11
return "0123456789abcdef".subString(i, i + 1)value or expression?12
# end function
+static stringType? hexname?(int nparameter definitions?) {
// function1
var hname? = ""value or expression?;2
+if ((n < 1)condition?) {
3
hvariableName? = "0"value or expression?; // assignment4
} else {5
var mname? = nvalue or expression?;6
+while (m > 0condition?) {
7
hvariableName? = hexDigit(m % 16) + hvalue or expression?; // assignment8
mvariableName? = divAsInt(m, 16)value or expression?; // assignment9
} // end while
} // end if
return hvalue or expression?;10
} // end function
+static stringType? hexDigitname?(int iparameter definitions?) {
// function11
return "0123456789abcdef".subString(i, i + 1)value or expression?;12
} // end function
+Function hexname?(n As Integerparameter definitions?) As StringType?
1
Dim hname? = ""value or expression? ' variable definition2
+If (n < 1)condition? Then
3
hvariableName? = "0"value or expression? ' assignment4
Else5
Dim mname? = nvalue or expression? ' variable definition6
+While m > 0condition?
7
hvariableName? = hexDigit(m Mod 16) + hvalue or expression? ' assignment8
mvariableName? = divAsInt(m, 16)value or expression? ' assignment9
End While
End If
Return hvalue or expression?10
End Function
+Function hexDigitname?(i As Integerparameter definitions?) As StringType?
11
Return "0123456789abcdef".subString(i, i + 1)value or expression?12
End Function
public class Global {
+static StringType? hexname?(int nparameter definitions?) {
// function1
var hname? = ""value or expression?;2
+if ((n < 1)condition?) {
3
hvariableName? = "0"value or expression?; // assignment4
} else {5
var mname? = nvalue or expression?;6
+while (m > 0condition?) {
7
hvariableName? = hexDigit(m % 16) + hvalue or expression?; // assignment8
mvariableName? = divAsInt(m, 16)value or expression?; // assignment9
} // end while
} // end if
return hvalue or expression?;10
} // end function
+static StringType? hexDigitname?(int iparameter definitions?) {
// function11
return "0123456789abcdef".subString(i, i + 1)value or expression?;12
} // end function
}
// end Global
Example of large numbers
● This code calculates 2 raised to the power of 50 through 72, and its output is shown below:
+main
13
+for nitem? in range(50, 73)source?
14
variable npname? set to pow(2, n).floor()value or expression?15
call printTabprocedureName?(n.toString().length(), $"{n}"arguments?)16
call printTabprocedureName?(30 - np.toString().length(), $"{np}\n"arguments?)17
end for
end main
+def main() -> None:
18
+for nitem? in range(50, 73)source?:
19
npname? = pow(2, n).floor()value or expression? # variable definition20
printTabprocedureName?(n.toString().length(), f"{n}"arguments?) # procedure call21
printTabprocedureName?(30 - np.toString().length(), f"{np}\n"arguments?) # procedure call22
# end for
# end main
+static void main() {
23
+foreach (var nitem? in range(50, 73)source?) {
24
var npname? = pow(2, n).floor()value or expression?;25
printTabprocedureName?(n.toString().length(), $"{n}"arguments?); // procedure call26
printTabprocedureName?(30 - np.toString().length(), $"{np}\n"arguments?); // procedure call27
} // end foreach
} // end main
+Sub main()
28
+For Each nitem? In range(50, 73)source?
29
Dim npname? = pow(2, n).floor()value or expression? ' variable definition30
printTabprocedureName?(n.toString().length(), $"{n}"arguments?) ' procedure call31
printTabprocedureName?(30 - np.toString().length(), $"{np}\n"arguments?) ' procedure call32
Next n
End Sub
+static void main() {
33
+foreach (var nitem? in range(50, 73)source?) {
34
var npname? = pow(2, n).floor()value or expression?;35
printTabprocedureName?(n.toString().length(), String.format("%", n)arguments?); // procedure call36
printTabprocedureName?(30 - np.toString().length(), String.format("%\n", np)arguments?); // procedure call37
} // end foreach
} // end main

Floating point
A floating point number is a decimal number (also known as a Real number) that may have both integer and fractional parts.
Its type is FloatfloatdoubleDoubledouble.
It may be written using exponential (scientific) notation, e.g.
120.0120.0120.0120.0120.0 can be written as 1.20e21.20e21.20e21.20e21.20e2, and
0.0120.0120.0120.0120.012 as 1.20e-21.20e-21.20e-21.20e-21.20e-2
name of type |
examples of defining a literal value |
FloatfloatdoubleDoubledouble |
+constant phiname? set to 1.618033988749895literal value or data structure?10+phiname? = 1.618033988749895literal value or data structure? # constant11+const Float phiname? = 1.618033988749895literal value or data structure?;12+Const phiname? = 1.618033988749895literal value or data structure?13+static final Float phiname? = 1.618033988749895literal value or data structure?; // constant14 |
FloatfloatdoubleDoubledouble |
variable readingname? set to 1.1e-10value or expression?15readingname? = 1.1e-10value or expression? # variable definition16var readingname? = 1.1e-10value or expression?;17Dim readingname? = 1.1e-10value or expression? ' variable definition18var readingname? = 1.1e-10value or expression?;19 |
Function dot methods on a FloatfloatdoubleDoubledouble
function dot method |
argument types |
return type |
returns |
| ceiling |
(none) |
IntintintIntegerint |
the first integral value larger than or equal to the argument's floating point value |
| equals |
FloatfloatdoubleDoubledouble |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if floating point number and argument values are equal – falseFalsefalseFalsefalse otherwise |
| floor |
(none) |
IntintintIntegerint |
the first integral value smaller than or equal to the argument's floating point value |
| isInfinite |
(none) |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if value would be infinite, e.g. after division by zero – falseFalsefalseFalsefalse otherwise |
| isNaN |
(none) |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if value is 'NaN', i.e. Not a Number, e.g. 0/0 – falseFalsefalseFalsefalse otherwise |
| notEqualTo |
FloatfloatdoubleDoubledouble |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if floating point number and argument values are unequal – falseFalsefalseFalsefalse otherwise |
| round |
IntintintIntegerint |
FloatfloatdoubleDoubledouble |
the value rounded (up or down as appropriate) to the number of decimal places specified in the argument |
| toString |
(none) |
StringstrstringStringString |
a string of decimal digits and decimal point representing the argument's floating point value |
Notes
- The limits on floating point numbers are:
- Maximum value: just over 1.0 × 10308
- Minimum value: approximately 5.0 × 10-324
- A variable that has been defined as being of type
FloatfloatdoubleDoubledouble may not be passed as an argument into a method that requires an IntintintIntegerint,
nor as an index into a ListlistListListList even if the variable contains no fractional part.
It may, however, be converted into an IntintintIntegerint before passing, using the function floor or ceiling.
- If you wish to define a variable to be of type
FloatfloatdoubleDoubledouble, but initialise it with an integer value, then add .0 on the end of the whole number, as in:
variable hoursWorkedname? set to 3.0value or expression?20hoursWorkedname? = 3.0value or expression? # variable definition21var hoursWorkedname? = 3.0value or expression?;22Dim hoursWorkedname? = 3.0value or expression? ' variable definition23var hoursWorkedname? = 3.0value or expression?;24
- Any variable or expression that evaluates to an
IntintintIntegerint may always be used where a FloatfloatdoubleDoubledouble is expected.
Boolean
A Boolean value is either trueTruetrueTruetrue or falseFalsefalseFalsefalse.
Its type is BooleanboolboolBooleanboolean.
The words trueTruetrueTruetrue and falseFalsefalseFalsefalse must be written in lower case.
name of type |
examples of defining a literal value |
BooleanboolboolBooleanboolean |
variable donename? set to truevalue or expression?25donename? = Truevalue or expression? # variable definition26var donename? = truevalue or expression?;27Dim donename? = Truevalue or expression? ' variable definition28var donename? = truevalue or expression?;29 |
Function dot methods on a BooleanboolboolBooleanboolean
function dot methods |
argument types |
return type |
returns |
| equals |
BooleanboolboolBooleanboolean |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if the truth value and argument are equal – falseFalsefalseFalsefalse otherwise |
| notEqualTo |
BooleanboolboolBooleanboolean |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if the truth value and argument are unequal – falseFalsefalseFalsefalse otherwise |
| toString |
(none) |
StringstrstringStringString |
String "true" if trueTruetrueTruetrue, "false" if falseFalsefalseFalsefalse |
Reference data types
String
The data type StringstrstringStringString represents text, i.e. a sequence of zero or more characters.
name of type |
examples of defining a literal value |
details |
StringstrstringStringString |
+constant titlename? set to "Ulysses"literal value or data structure?30+titlename? = "Ulysses"literal value or data structure? # constant31+const String titlename? = "Ulysses"literal value or data structure?;32+Const titlename? = "Ulysses"literal value or data structure?33+static final String titlename? = "Ulysses"literal value or data structure?; // constant34 |
delimited by double quotes |
StringstrstringStringString |
variable quotename? set to "'Hello', she said"value or expression?35quotename? = "'Hello', she said"value or expression? # variable definition36var quotename? = "'Hello', she said"value or expression?;37Dim quotename? = "'Hello', she said"value or expression? ' variable definition38var quotename? = "'Hello', she said"value or expression?;39 |
' may be used in a string delimited by " |
StringstrstringStringString |
variable emptyStringname? set to ""value or expression?40emptyStringname? = ""value or expression? # variable definition41var emptyStringname? = ""value or expression?;42Dim emptyStringname? = ""value or expression? ' variable definition43var emptyStringname? = ""value or expression?;44 |
a zero-length, or 'empty', string |
Character sets
When typing from the keyboard into a literal string all the basic ASCII characters (0x20 to 0x7e) and '£' can be input.
You cannot use Alt+numeric-keypad to enter accented letters or other special characters in the extended ASCII range (0x80 to 0xff).
You can, however, copy any text from outside Elan and paste it into a string, whether ASCII, extended ASCII or UTF-8 encoded.
To insert a character from the full range, you use its Unicode (codepoint) value, in decimal or hexadecimal, by means of function unicode :
print($"Spanish introduces a question with {unicode(191)}")print(f"Spanish introduces a question with {unicode(191)}")print($"Spanish introduces a question with {unicode(191)}")print($"Spanish introduces a question with {unicode(191)}")print(String.format("Spanish introduces a question with %", unicode(191)))
|
⟶ | Spanish introduces a question with ¿ |
print($"This is an up arrow: {unicode(0x2191)}")print(f"This is an up arrow: {unicode(0x2191)}")print($"This is an up arrow: {unicode(0x2191)}")print($"This is an up arrow: {unicode(&H2191)}")print(String.format("This is an up arrow: %", unicode(0x2191)))
|
⟶ | This is an up arrow: ↑
|
These examples 'interpolate' the output of function unicode by using a $ before the string and curly braces within it.
See Interpolated fields ).
Manipulating strings
Strings can be built from other strings by concatenation using the plus operator, for example:
print("Hello " + "world")print("Hello " + "world")print("Hello " + "world")print("Hello " + "world")print("Hello " + "world")
| ⟶ | Hello world |
A newline may be inserted within a string with \n:
print("Hello\nworld")print("Hello\nworld")print("Hello\nworld")print("Hello\nworld")print("Hello\nworld") | ⟶ | Hello world |
When editing and you leave the field, the newline will be implicitly applied in your code.
As in most languages, strings are immutable. When you apply any operation or function with the intent of modifying an existing StringstrstringStringString, the existing StringstrstringStringString is never changed. Instead, the operation or function will return a new StringstrstringStringString that is based on the original, but with the specified differences.
You can loop through a StringstrstringStringString picking each of its characters sequentially using the for loop .
Function dot methods on a String
function dot method |
argument types |
return type |
returns |
| asRegExp |
(none) |
RegExpRegExpRegExpRegExpRegExp |
a new string that is a a converted to a regular expression: no check is made of whether the result is a valid regular expression |
| asUnicode |
(none) |
IntintintIntegerint |
the Unicode value of the first character of the string
(To convert a Unicode value into a string, use function unicode ) |
| contains |
(none) |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if the string contains the substring specified as the argument – falseFalsefalseFalsefalse otherwise |
| equals |
StringstrstringStringString |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if the string and argument are equal – falseFalsefalseFalsefalse otherwise |
| notEqualTo |
StringstrstringStringString |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if the string and argument are unequal – falseFalsefalseFalsefalse otherwise |
| indexOf |
StringstrstringStringString |
IntintintIntegerint |
index of the first instance of the argument (substring) within the string If it is not present, -1 is returned |
| isAfter |
StringstrstringStringString |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if alphabetic comparison finds the string comes strictly 'after' the argument string – falseFalsefalseFalsefalse otherwise |
| isAfterOrSameAs |
StringstrstringStringString |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if alphabetic comparison finds the string comes 'after' or equals the argument string – falseFalsefalseFalsefalse otherwise |
| isBefore |
StringstrstringStringString |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if alphabetic comparison finds the string comes strictly 'before' the argument string – falseFalsefalseFalsefalse otherwise |
| isBeforeOrSameAs |
StringstrstringStringString |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if alphabetic comparison finds the string comes 'before' or equals the argument string – falseFalsefalseFalsefalse otherwise |
| length |
(none) |
IntintintIntegerint |
the number of characters in the string |
| lowerCase |
(none) |
StringstrstringStringString |
a new string with the original rendered in lower case |
| matchesRegExp |
RegExpRegExpRegExpRegExpRegExp |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if the string matches the regular expression – falseFalsefalseFalsefalse otherwise |
| replace |
StringstrstringStringString, StringstrstringStringString |
StringstrstringStringString |
a new string with all occurrences of the first argument string replaced by the second argument string |
| split |
StringstrstringStringString |
List<of String>list[str]List<string>List(Of String)List<String> |
a ListlistListListList of the substrings found between occurrences of the argument string
if the argument is the empty string then the ListlistListListList is of all the individual characters |
| subString |
IntintintIntegerint, IntintintIntegerint |
StringstrstringStringString |
a new string that is the substring specified by the two positive integers (m,n) where
m indexes the first character of the substring required (counting from 0) and
n indexes the character after the last character required (exclusive index)
if m ≥ n the result is the empty string
|
| toString |
(none) |
StringstrstringStringString |
the string itself |
| trim |
(none) |
StringstrstringStringString |
a new string with leading and trailing spaces removed |
| upperCase |
(none) |
StringstrstringStringString |
a new string with the original rendered in upper case |
Interpolated fields in strings
Strings support interpolation, that is you can insert the values of variables
or simple expressions within the string by enclosing them in curly braces and
prefixing the string with a $:
If aaaaa and bbbbb have values 3 and 17:
print($"{a} times {b} equals {a*b}")print(f"{a} times {b} equals {a*b}")print($"{a} times {b} equals {a*b}")print($"{a} times {b} equals {a*b}")print(String.format("% times % equals %", a, b, a*b)) |
⟶ | 3 times 17 equals 51 |
If velocityvelocityvelocityvelocityvelocity and fuelfuelfuelfuelfuel have values 3.0 and 50.4:
assign messagevariableName? to $"LANDED SAFELY AT SPEED {(velocity*100).floor()} FUEL {fuel.floor()}"value or expression?45messagevariableName? = f"LANDED SAFELY AT SPEED {(velocity*100).floor()} FUEL {fuel.floor()}"value or expression? # assignment46messagevariableName? = $"LANDED SAFELY AT SPEED {(velocity*100).floor()} FUEL {fuel.floor()}"value or expression?; // assignment47messagevariableName? = $"LANDED SAFELY AT SPEED {(velocity*100).floor()} FUEL {fuel.floor()}"value or expression? ' assignment48messagevariableName? = String.format("LANDED SAFELY AT SPEED % FUEL %", (velocity*100).floor(), fuel.floor())value or expression?; // assignment49
print(message)print(message)print(message)print(message)print(message)
|
⟶ | LANDED SAFELY AT SPEED 300 FUEL 50 |
And for the area of a circle:
+main
38
variable rname? set to 2.0value or expression?39
print($"area = {(pi*r*r).round(2)}"value or expression?)40
end main
+def main() -> None:
41
rname? = 2.0value or expression? # variable definition42
print(f"area = {(pi*r*r).round(2)}"value or expression?)43
# end main
+static void main() {
44
var rname? = 2.0value or expression?;45
Console.WriteLine($"area = {(pi*r*r).round(2)}"value or expression?); // print statement46
} // end main
+Sub main()
47
Dim rname? = 2.0value or expression? ' variable definition48
Console.WriteLine($"area = {(pi*r*r).round(2)}"value or expression?) ' print statement49
End Sub
+static void main() {
50
var rname? = 2.0value or expression?;51
System.out.println(String.format("area = %", (pi*r*r).round(2))value or expression?); // print statement52
} // end main
|
⟶ |
area = 12.57
|
Standard data structures
Elan has two mutable data structure types ListlistListListList and DictionaryDictionaryDictionaryDictionaryDictionary, and
three immutable data structure types HashSetHashSetHashSetHashSetHashSet, StackStackStackStackStack and QueueQueueQueueQueueQueue.
The contents of these structures are referred to as items (or sometimes elements).
The values of items in a mutable structure may be changed directly by calling the various procedure dot methods defined for each structure type.
The values of items in an immutable structure cannot be changed directly, and so have no procedure dot methods defined for them:
rather, the methods called on them create new copies of the structures containing specified changes.
Since procedure methods may be called only from within the main routine or a procedure,
it is also possible to make changes via function dot methods, which return a copy of the data structure
with specified changes: that is why all such methods have names starting 'with'.
Immutable data structures are intended specifically to facilitate the functional programming paradigm,
but some are also useful within other programming paradigms.
All six contain values (and keys in the case of a DictionaryDictionaryDictionaryDictionaryDictionary) of only a single type, that type being specified either explicitly
(as in <of IntintintIntegerint>), or implicitly if the structure is created using a literal definition.
This table summarises the creation and reference to these structures. Details of their methods follow.
|
List |
Dictionary |
HashSet |
Stack |
Queue |
| mutability |
Mutable |
Mutable |
Immutable |
Immutable |
Immutable |
| type form |
List<of Type>list[Type]List<Type>List(Of Type)List<Type> The type of item can be any, including ListlistListListList for 'jagged' data |
new codenew codenew codenew codepublic class Global {
new code
} // end Global
keyTypekeyTypekeyTypekeyTypekeyType is IntintintIntegerint, FloatfloatdoubleDoubledouble, StringstrstringStringString or BooleanboolboolBooleanboolean
valueTypevalueTypevalueTypevalueTypevalueType may be any type |
HashSet<of Type>HashSet[Type]HashSet<Type>HashSet(Of Type)HashSet<Type> The type of the item must be immutable |
Stack<of Type>Stack[Type]Stack<Type>Stack(Of Type)Stack<Type> The type of the item must be immutable |
Queue<of Type>Queue[Type]Queue<Type>Queue(Of Type)Queue<Type> The type of the item must be immutable |
| size | Dynamic | Dynamic | Dynamic | Dynamic | Dynamic |
| literal definition |
[2, 3, 5, 7, 11][2, 3, 5, 7, 11]new [] {2, 3, 5, 7, 11}{2, 3, 5, 7, 11}list(2, 3, 5, 7, 11) |
Not available |
Only as converted from a literal ListlistListListList e.g. ["a", "b", "c"].asSet()["a", "b", "c"].asSet()new [] {"a", "b", "c"}.asSet(){"a", "b", "c"}.asSet()list("a", "b", "c").asSet() |
Not available |
Not available |
| create empty |
new List<of Type>()list[Type]()new List<Type>()New List(Of Type)()new List<Type>() |
new codenew codenew codenew codepublic class Global {
new code
} // end Global |
new HashSet<of Type>()HashSet[Type]()new HashSet<Type>()New HashSet(Of Type)()new HashSet<Type>() |
new Stack<of Type>()Stack[Type]()new Stack<Type>()New Stack(Of Type)()new Stack<Type>() |
new Queue<of Type>()Queue[Type]()new Queue<Type>()New Queue(Of Type)()new Queue<Type>() |
| create initialised |
createPopulatedList(number, value)createPopulatedList(number, value)createPopulatedList(number, value)createPopulatedList(number, value)createPopulatedList(number, value)
createPopulatedListofLists(cols, rows, value)createPopulatedListofLists(cols, rows, value)createPopulatedListofLists(cols, rows, value)createPopulatedListofLists(cols, rows, value)createPopulatedListofLists(cols, rows, value)
| createDictionary(List<of (keyType, valueType)>) |
Not available |
Not available |
Not available |
| read by index |
li[2]li[2]li[2]li[2]li[2] |
d["b"]d["b"]d["b"]d["b"]d["b"] |
not available |
not available |
not available |
| read by index range |
li.subList(3, 5)li.subList(3, 5)li.subList(3, 5)li.subList(3, 5)li.subList(3, 5) lower bound is inclusive from 0 upper bound is exclusive |
not available |
not available |
not available |
not available |
| procedure methods to mutate contents |
see Procedure methods on a ListlistListListList |
see Procedure methods on a Dictionary |
not available |
not available |
not available |
| function dot methods |
see Function dot methods on a ListlistListListList |
see Function dot methods on a Dictionary |
see Function dot methods on a Set |
see Function dot methods on a Stack |
see Function dot methods on a Queue |
List
The ListlistListListList type defines a data structure containing n items of any single type,
including basic value types, structure types such as ListlistListListList,
and user-defined types such as a class.
Items in a ListlistListListList of n items are indexed from 0 to n-1.
To create a ListlistListListList, use either of:
- Method createPopulatedList to define its length and the initial value (and implicitly the type) of its items:
variable aListname? set to createPopulatedList(10, "no one")value or expression?1aListname? = createPopulatedList(10, "no one")value or expression? # variable definition2var aListname? = createPopulatedList(10, "no one")value or expression?;3Dim aListname? = createPopulatedList(10, "no one")value or expression? ' variable definition4var aListname? = createPopulatedList(10, "no one")value or expression?;5
- Define an empty
ListlistListListList of the required type, and use the procedure methods listed below to populate it:
variable aListname? set to new List<of String>()value or expression?6aListname? = list[str]()value or expression? # variable definition7var aListname? = new List<string>()value or expression?;8Dim aListname? = New List(Of String)()value or expression? ' variable definition9var aListname? = new List<String>()value or expression?;10
call aList.initialiseprocedureName?(10, "no one"arguments?)11aList.initialiseprocedureName?(10, "no one"arguments?) # procedure call12aList.initialiseprocedureName?(10, "no one"arguments?); // procedure call13aList.initialiseprocedureName?(10, "no one"arguments?) ' procedure call14aList.initialiseprocedureName?(10, "no one"arguments?); // procedure call15
call aList.appendprocedureName?("4"arguments?)16aList.appendprocedureName?("4"arguments?) # procedure call17aList.appendprocedureName?("4"arguments?); // procedure call18aList.appendprocedureName?("4"arguments?) ' procedure call19aList.appendprocedureName?("4"arguments?); // procedure call20
The item at index ixixixixix in ListlistListListList aListaListaListaListaList can then be changed using an assign variable instruction and a valid index value in square brackets:
assign aList[ix]variableName? to "Smith"value or expression?21aList[ix]variableName? = "Smith"value or expression? # assignment22aList[ix]variableName? = "Smith"value or expression?; // assignment23aList(ix)variableName? = "Smith"value or expression? ' assignment24aList[ix]variableName? = "Smith"value or expression?; // assignment25
A ListlistListListList's size can be dynamically changed using the procedure methods listed below.
Deconstructing a List
A ListlistListListList may be split (deconstructed) into new named values using indexes and
the methods head, tail and subList :
- To extract the first item in a
ListlistListListList:
variable headItemname? set to myList[0]value or expression?26headItemname? = myList[0]value or expression? # variable definition27var headItemname? = myList[0]value or expression?;28Dim headItemname? = myList(0)value or expression? ' variable definition29var headItemname? = myList[0]value or expression?;30
or
assign headItemvariableName? to myList.head()value or expression?31headItemvariableName? = myList.head()value or expression? # assignment32headItemvariableName? = myList.head()value or expression?; // assignment33headItemvariableName? = myList.head()value or expression? ' assignment34headItemvariableName? = myList.head()value or expression?; // assignment35
- To form a new
ListlistListListList of all but the first item in a ListlistListListList:
new codenew codenew codenew codepublic class Global {
new code
} // end Global
If the original ListlistListListList contains only one item, the new ListlistListListList will be the empty ListlistListListList.
- To get some other portion of a
ListlistListListList, use the method subList:
assign shortListvariableName? to myList.subList(1, 5)value or expression?1shortListvariableName? = myList.subList(1, 5)value or expression? # assignment2shortListvariableName? = myList.subList(1, 5)value or expression?; // assignment3shortListvariableName? = myList.subList(1, 5)value or expression? ' assignment4shortListvariableName? = myList.subList(1, 5)value or expression?; // assignment5
In all these cases the items indexed must exist, else a runtime error will stop the program.
Lists of lists
Two dimensional arrays
Understood as a grid, a 2D array is a ListlistListListList of 'columns' each of which is a ListlistListListList of 'row' items, i.e. it is a ListlistListListList of ListlistListListLists in which the column number is the x coordinate, and the row number is the y coordinate.
To create a 2D array that holds a value of a single type in every cell, you define such a ListlistListListList of ListlistListListLists thus:
- Use method createPopulatedListofLists to set the size of, and initial value in, every x,y position:
variable array2Dname? set to createPopulatedListofLists(cols, rows, value)value or expression?6array2Dname? = createPopulatedListofLists(cols, rows, value)value or expression? # variable definition7var array2Dname? = createPopulatedListofLists(cols, rows, value)value or expression?;8Dim array2Dname? = createPopulatedListofLists(cols, rows, value)value or expression? ' variable definition9var array2Dname? = createPopulatedListofLists(cols, rows, value)value or expression?;10
- For the special case of Block graphics , use 40 columns and 30 rows or (more simply):
variable gridname? set to createBlockGraphics(value)value or expression?11gridname? = createBlockGraphics(value)value or expression? # variable definition12var gridname? = createBlockGraphics(value)value or expression?;13Dim gridname? = createBlockGraphics(value)value or expression? ' variable definition14var gridname? = createBlockGraphics(value)value or expression?;15
The item at index ixixixixix,iyiyiyiyiy in a 2D array can be accessed and changed
using its two coordinates in square brackets:
variable valuename? set to array2D[ix][iy]value or expression?16valuename? = array2D[ix][iy]value or expression? # variable definition17var valuename? = array2D[ix][iy]value or expression?;18Dim valuename? = array2D(ix)(iy)value or expression? ' variable definition19var valuename? = array2D[ix][iy]value or expression?;20
assign array2D[ix][iy]variableName? to 7value or expression?21array2D[ix][iy]variableName? = 7value or expression? # assignment22array2D[ix][iy]variableName? = 7value or expression?; // assignment23array2D(ix)(iy)variableName? = 7value or expression? ' assignment24array2D[ix][iy]variableName? = 7value or expression?; // assignment25
Higher dimensional arrays
For a 3D array, you can, for example, define:
-
variable array3Dname? set to new List<of List<of List<of Float>>>()value or expression?26array3Dname? = list[list[list[float]]]()value or expression? # variable definition27var array3Dname? = new List<List<List<double>>>()value or expression?;28Dim array3Dname? = New List(Of List(Of List(Of Double)))()value or expression? ' variable definition29var array3Dname? = new List<List<List<double>>>()value or expression?;30
and refer to a cell using three indexes in square brackets.
Procedure methods on a ListlistListListList
Where an argument provides a new value for an item in a ListlistListListList, that value must be of the same type as defined for the ListlistListListList's items.
procedure method |
arguments |
action |
| append |
value of ListlistListListList item's type |
the item is added to the end of the ListlistListListList |
| appendList |
ListlistListListList |
the argument ListlistListListList is added to the end of the ListlistListListList |
| initialise |
IntintintIntegerint, value of ListlistListListList item's type |
specify the number (> 0) of items in the ListlistListListList, and an initial value for every item.
May be called at any time to redefine the ListlistListListList's size and initial values. |
| insert |
IntintintIntegerint, value of ListlistListListList item's type |
the item is inserted at the index given.
If the index is negative it is counted from the end
If the index is greater than the ListlistListListList's length, the item is inserted at the end |
| prepend |
value of ListlistListListList item's type |
the item is is added to the start of the ListlistListListList |
| prependList |
ListlistListListList |
the argument ListlistListListList is added to the start of the ListlistListListList |
| removeAll |
value of ListlistListListList item's type |
delete all items equal to the given item |
| removeAt |
IntintintIntegerint |
delete the item at the argument index |
| removeFirst |
value of ListlistListListList item's type |
delete the first item equal to the given value |
Function dot methods on a ListlistListListList
function dot method |
arguments |
return type |
returns |
| asSet |
(none) |
HashSetHashSetHashSetHashSetHashSet |
a new Set containing all the unique items in the ListlistListListList |
| contains |
value |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if the ListlistListListList contains the specified item
– falseFalsefalseFalsefalse otherwise |
| equals |
ListlistListListList |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if ListlistListListList and argument are identical – falseFalsefalseFalsefalse otherwise |
| filter |
lambdalambdalambdalambdalambda |
ListlistListListList |
a new ListlistListListList obtained from applying a lambda to the input ListlistListListList
see filter in HoFs |
| head |
(none) |
ListlistListListList item's type |
the first item of the ListlistListListList (i.e. index = 0, which must exist) |
| indexOf |
value of ListlistListListList item's type |
IntintintIntegerint |
the index of the first occurrence of the argument value in the ListlistListListList, or -1 if no match is found |
| join |
List<of String>list[str]List<string>List(Of String)List<String> |
StringstrstringStringString |
a single String that joins all the items in the ListlistListListList, with the specified String (which can be empty) inserted between the items |
| length |
(none) |
IntintintIntegerint |
the number of items in the ListlistListListList |
| map |
lambdalambdalambdalambdalambda |
ListlistListListList |
a new ListlistListListList obtained from applying a lambda to the input ListlistListListList
see map in HoFs |
| maxBy |
lambdalambdalambdalambdalambda |
ListlistListListList item's type |
the ListlistListListList item corresponding to the maximum of the values returned by a lambda
see maxBy in HoFs |
| minBy |
lambdalambdalambdalambdalambda |
ListlistListListList item's type |
the ListlistListListList item corresponding to the minimum of the values returned by a lambda
see minBy in HoFs |
| notEqualTo |
ListlistListListList |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if ListlistListListList and argument differ l – falseFalsefalseFalsefalse otherwise |
| orderBy |
lambdalambdalambdalambdalambda |
ListlistListListList |
a new ListlistListListList with the items ordered according to the value returned by a lambda |
| reduce |
item of ListlistListListList item's type,
lambdalambdalambdalambdalambda |
return type of lambda |
the final value obtained by applying a lambda cumulatively to each item in the input ListlistListListList
taking account of the first argument as an initial (and default return) value
see reduce in HoFs |
| subList |
IntintintIntegerint, IntintintIntegerint |
ListlistListListList |
a new ListlistListListList that contains the items specified by the two positive integers (m,n) where
m indexes the first item of the ListlistListListList required (counting from 0) and
n indexes the item after the last item required (exclusive index)
if m ≥ n the result is the empty ListlistListListList
|
| tail |
(none) |
ListlistListListList item's type |
all items except the first item in the ListlistListListList (i.e. index = 1..n, which must exist) |
| toString |
(none) |
StringstrstringStringString |
a String that is a comma+space-separated list of the ListlistListListList's items, enclosed in square brackets |
| withAppend |
item of ListlistListListList item's type |
ListlistListListList |
a new ListlistListListList lengthened with the item added after the end |
| withAppendList |
ListlistListListList of same type |
ListlistListListList |
a new ListlistListListList lengthened by appending the given ListlistListListList |
| withInsert |
IntintintIntegerint, value of ListlistListListList item's type |
ListlistListListList |
a new ListlistListListList with the item inserted after the item at the given index position |
| withPrepend |
value of ListlistListListList item's type |
ListlistListListList |
a new ListlistListListList lengthened with the item added before the beginning |
| withPrependList |
ListlistListListList of same type |
ListlistListListList |
a new ListlistListListList lengthened by prepending the given ListlistListListList |
| withRemoveAll |
value of ListlistListListList item's type |
ListlistListListList |
a new ListlistListListList with items equal to the given item removed |
| withRemoveAt |
IntintintIntegerint |
ListlistListListList |
a new ListlistListListList with the item at the given index removed |
| withRemoveFirst |
value of ListlistListListList item's type |
ListlistListListList |
a new ListlistListListList with the first item equal to the given item removed |
| withPut (supersedes deprecated withSet) |
IntintintIntegerint, value of ListlistListListList item's type |
ListlistListListList |
a new ListlistListListList with the item replacing that at the given index |
Dictionary
A DictionaryDictionaryDictionaryDictionaryDictionary is like a ListlistListListList whose items are pairs but, instead of having a numeric index, each item has a key plus an associated value,
i.e. a Dictionary is a set of key:value pairs.
The key's type must be one of IntintintIntegerint, FloatfloatdoubleDoubledouble, StringstrstringStringString or BooleanboolboolBooleanboolean.
The values may be of any type. The types of both keys and values are fixed when the Dictionary is created.
You refer to a dictionary item using one of its (unique) keys, e.g. in a Dictionary<of String, Int>Dictionary[str, int]Dictionary<string, int>Dictionary(Of String, Integer)Dictionary<String, int> named birthdaysbirthdaysbirthdaysbirthdaysbirthdays
whose keys are names and whose values are birth year, you might refer to birthdays["Shakespeare"]birthdays["Shakespeare"]birthdays["Shakespeare"]birthdays["Shakespeare"]birthdays["Shakespeare"] and retrieve the value 1564.
Example using DictionaryDictionaryDictionaryDictionaryDictionary
● Define a constant dictionary for reference throughout the program:
Procedure greekLetters sets up the key:value pairs, procedure printD shows how a procedure can use the dictionary,
and function getDItem retrieves a value given a key.
+main
1
variable dLname? set to new Dictionary<of String, Int>()value or expression?2
variable dLRefname? set to new AsRef<of Dictionary<of String, Int>>(dL)value or expression?3
call greekLettersprocedureName?(dLRefarguments?)4
assign dLvariableName? to dLRef.value()value or expression?5
print(dLvalue or expression?)6
call printDprocedureName?(dLarguments?)7
print(getDItem(dL, "alpha")value or expression?)8
end main
+procedure printDname?(dL as Dictionary<of String, Int>parameter definitions?)
9
print(dLvalue or expression?)10
end procedure
+function getDItemname?(dL as Dictionary<of String, Int>, k as Stringparameter definitions?) returns IntType?
11
return dL[k]value or expression?12
end function
+procedure printDItemname?(dL as Dictionary<of String, Int>, k as Stringparameter definitions?)
13
print(dL[k]value or expression?)14
end procedure
+procedure greekLettersname?(d as AsRef<of Dictionary<of String, Int>>parameter definitions?)
15
variable diname? set to new Dictionary<of String, Int>()value or expression?16
assign di["alpha"]variableName? to 1value or expression?17
assign di["beta"]variableName? to 2value or expression?18
assign di["gamma"]variableName? to 3value or expression?19
call d.putprocedureName?(diarguments?)20
end procedure
+def main() -> None:
1
dLname? = Dictionary[str, int]()value or expression? # variable definition2
dLRefname? = AsRef[Dictionary[str, int]](dL)value or expression? # variable definition3
greekLettersprocedureName?(dLRefarguments?) # procedure call4
dLvariableName? = dLRef.value()value or expression? # assignment5
print(dLvalue or expression?)6
printDprocedureName?(dLarguments?) # procedure call7
print(getDItem(dL, "alpha")value or expression?)8
# end main
+def printDname?(dL: Dictionary[str, int]parameter definitions?) -> None:
# procedure9
print(dLvalue or expression?)10
# end procedure
+def getDItemname?(dL: Dictionary[str, int], k: strparameter definitions?) -> intType?:
# function11
return dL[k]value or expression?12
# end function
+def printDItemname?(dL: Dictionary[str, int], k: strparameter definitions?) -> None:
# procedure13
print(dL[k]value or expression?)14
# end procedure
+def greekLettersname?(d: AsRef[Dictionary[str, int]]parameter definitions?) -> None:
# procedure15
diname? = Dictionary[str, int]()value or expression? # variable definition16
di["alpha"]variableName? = 1value or expression? # assignment17
di["beta"]variableName? = 2value or expression? # assignment18
di["gamma"]variableName? = 3value or expression? # assignment19
d.putprocedureName?(diarguments?) # procedure call20
# end procedure
main()
+static void main() {
1
var dLname? = new Dictionary<string, int>()value or expression?;2
var dLRefname? = new AsRef<Dictionary<string, int>>(dL)value or expression?;3
greekLettersprocedureName?(dLRefarguments?); // procedure call4
dLvariableName? = dLRef.value()value or expression?; // assignment5
Console.WriteLine(dLvalue or expression?); // print statement6
printDprocedureName?(dLarguments?); // procedure call7
Console.WriteLine(getDItem(dL, "alpha")value or expression?); // print statement8
} // end main
+static void printDname?(Dictionary<string, int> dLparameter definitions?) {
// procedure9
Console.WriteLine(dLvalue or expression?); // print statement10
} // end procedure
+static intType? getDItemname?(Dictionary<string, int> dL, string kparameter definitions?) {
// function11
return dL[k]value or expression?;12
} // end function
+static void printDItemname?(Dictionary<string, int> dL, string kparameter definitions?) {
// procedure13
Console.WriteLine(dL[k]value or expression?); // print statement14
} // end procedure
+static void greekLettersname?(AsRef<Dictionary<string, int>> dparameter definitions?) {
// procedure15
var diname? = new Dictionary<string, int>()value or expression?;16
di["alpha"]variableName? = 1value or expression?; // assignment17
di["beta"]variableName? = 2value or expression?; // assignment18
di["gamma"]variableName? = 3value or expression?; // assignment19
d.putprocedureName?(diarguments?); // procedure call20
} // end procedure
+Sub main()
1
Dim dLname? = New Dictionary(Of String, Integer)()value or expression? ' variable definition2
Dim dLRefname? = New AsRef(Of Dictionary(Of String, Integer))(dL)value or expression? ' variable definition3
greekLettersprocedureName?(dLRefarguments?) ' procedure call4
dLvariableName? = dLRef.value()value or expression? ' assignment5
Console.WriteLine(dLvalue or expression?) ' print statement6
printDprocedureName?(dLarguments?) ' procedure call7
Console.WriteLine(getDItem(dL, "alpha")value or expression?) ' print statement8
End Sub
+Sub printDname?(dL As Dictionary(Of String, Integer)parameter definitions?)
' procedure9
Console.WriteLine(dLvalue or expression?) ' print statement10
End Sub
+Function getDItemname?(dL As Dictionary(Of String, Integer), k As Stringparameter definitions?) As IntegerType?
11
Return dL(k)value or expression?12
End Function
+Sub printDItemname?(dL As Dictionary(Of String, Integer), k As Stringparameter definitions?)
' procedure13
Console.WriteLine(dL(k)value or expression?) ' print statement14
End Sub
+Sub greekLettersname?(d As AsRef(Of Dictionary(Of String, Integer))parameter definitions?)
' procedure15
Dim diname? = New Dictionary(Of String, Integer)()value or expression? ' variable definition16
di("alpha")variableName? = 1value or expression? ' assignment17
di("beta")variableName? = 2value or expression? ' assignment18
di("gamma")variableName? = 3value or expression? ' assignment19
d.putprocedureName?(diarguments?) ' procedure call20
End Sub
public class Global {
+static void main() {
1
var dLname? = new Dictionary<String, int>()value or expression?;2
var dLRefname? = new AsRef<Dictionary<String, int>>(dL)value or expression?;3
greekLettersprocedureName?(dLRefarguments?); // procedure call4
dLvariableName? = dLRef.value()value or expression?; // assignment5
System.out.println(dLvalue or expression?); // print statement6
printDprocedureName?(dLarguments?); // procedure call7
System.out.println(getDItem(dL, "alpha")value or expression?); // print statement8
} // end main
+static void printDname?(Dictionary<String, int> dLparameter definitions?) {
// procedure9
System.out.println(dLvalue or expression?); // print statement10
} // end procedure
+static intType? getDItemname?(Dictionary<String, int> dL, String kparameter definitions?) {
// function11
return dL[k]value or expression?;12
} // end function
+static void printDItemname?(Dictionary<String, int> dL, String kparameter definitions?) {
// procedure13
System.out.println(dL[k]value or expression?); // print statement14
} // end procedure
+static void greekLettersname?(AsRef<Dictionary<String, int>> dparameter definitions?) {
// procedure15
var diname? = new Dictionary<String, int>()value or expression?;16
di["alpha"]variableName? = 1value or expression?; // assignment17
di["beta"]variableName? = 2value or expression?; // assignment18
di["gamma"]variableName? = 3value or expression?; // assignment19
d.putprocedureName?(diarguments?); // procedure call20
} // end procedure
}
// end Global
● Define a constant Dictionary for reference throughout the program
in a way suitable for functional programming, by using the HoF reduce in a function
that creates the Dictionary from a List of key:value pairs as Tuples:
+main
1
variable diname? set to createDictionary([("alpha", 1), ("beta", 2), ("gamma", 3)])value or expression?2
print(di["beta"]value or expression?)3
end main
+function createDictionaryname?(kvps as List<of (String, Int)>parameter definitions?) returns Dictionary<of String, Int>Type?
4
let dname? be new Dictionary<of String, Int>()value or expression?5
return kvps.reduce(d, lambda d as Dictionary<of String, Int>, kvp as (String, Int) => d.withPut(kvp.item_0, kvp.item_1))value or expression?6
end function
+def main() -> None:
1
diname? = createDictionary([("alpha", 1), ("beta", 2), ("gamma", 3)])value or expression? # variable definition2
print(di["beta"]value or expression?)3
# end main
+def createDictionaryname?(kvps: list[tuple[str, int]]parameter definitions?) -> Dictionary[str, int]Type?:
# function4
dname? = Dictionary[str, int]()value or expression? # let5
return kvps.reduce(d, lambda d: Dictionary[str, int], kvp: tuple[str, int]: d.withPut(kvp.item_0, kvp.item_1))value or expression?6
# end function
main()
+static void main() {
1
var diname? = createDictionary(new [] {("alpha", 1), ("beta", 2), ("gamma", 3)})value or expression?;2
Console.WriteLine(di["beta"]value or expression?); // print statement3
} // end main
+static Dictionary<string, int>Type? createDictionaryname?(List<(string, int)> kvpsparameter definitions?) {
// function4
var dname? = new Dictionary<string, int>()value or expression?; // let5
return kvps.reduce(d, Dictionary<string, int> d, (string, int) kvp => d.withPut(kvp.item_0, kvp.item_1))value or expression?;6
} // end function
+Sub main()
1
Dim diname? = createDictionary({("alpha", 1), ("beta", 2), ("gamma", 3)})value or expression? ' variable definition2
Console.WriteLine(di("beta")value or expression?) ' print statement3
End Sub
+Function createDictionaryname?(kvps As List(Of (String, Integer))parameter definitions?) As Dictionary(Of String, Integer)Type?
4
Dim dname? = New Dictionary(Of String, Integer)()value or expression? ' let5
Return kvps.reduce(d, Function (d As Dictionary(Of String, Integer), kvp As (String, Integer)) d.withPut(kvp.item_0, kvp.item_1))value or expression?6
End Function
public class Global {
+static void main() {
1
var diname? = createDictionary(list(("alpha", 1), ("beta", 2), ("gamma", 3)))value or expression?;2
System.out.println(di["beta"]value or expression?); // print statement3
} // end main
+static Dictionary<String, int>Type? createDictionaryname?(List<(String, int)> kvpsparameter definitions?) {
// function4
var dname? = new Dictionary<String, int>()value or expression?; // let5
return kvps.reduce(d, (Dictionary<String, int> d, (String, int) kvp) -> d.withPut(kvp.item_0, kvp.item_1))value or expression?;6
} // end function
}
// end Global
Procedure method on a DictionaryDictionaryDictionaryDictionaryDictionary
procedure method |
argument types |
action |
| removeAt |
key's type |
delete the key:pair at the given key (if it exists) |
Function dot methods on a DictionaryDictionaryDictionaryDictionaryDictionary
function dot method |
argument types |
return type |
returns |
| equals |
DictionaryDictionaryDictionaryDictionaryDictionary |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if dictionary and argument are identical – falseFalsefalseFalsefalse otherwise |
| hasKey |
item of Dictionary key's type |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if the Dictionary contains the given key – falseFalsefalseFalsefalse otherwise |
| keys |
(none) |
ListlistListListList |
a ListlistListListList containing the keys |
| notEqualTo |
DictionaryDictionaryDictionaryDictionaryDictionary |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if dictionary and argument differ – falseFalsefalseFalsefalse otherwise |
| toString |
(none) |
StringstrstringStringString |
a string that is a comma+space-separated list of the Dictionary's key:value pairs, enclosed in square brackets |
| values |
(none) |
ListlistListListList |
a ListlistListListList containing the values |
| withPut (supersedes deprecated withSet) |
item of Dictionary key's type, item of Dictionary value's type |
DictionaryDictionaryDictionaryDictionaryDictionary |
a new Dictionary with the value replacing what was at the specified key |
| withRemoveAt |
item of Dictionary key's type |
DictionaryDictionaryDictionaryDictionaryDictionary |
a new Dictionary with the key:value pair removed from the specified key |
HashSet
A HashSetHashSetHashSetHashSetHashSet is a standard data structure containing set members, that works somewhat like a ListlistListListList with two important differences:
- The value of a
HashSetHashSetHashSetHashSetHashSet member may appear only once: if a member being added to a HashSetHashSetHashSetHashSetHashSet has the same value as an existing member in the HashSetHashSetHashSetHashSetHashSet then the HashSetHashSetHashSetHashSetHashSet remains the same as before.
- The values in a
HashSetHashSetHashSetHashSetHashSet are not indexed: two HashSets with the same contents but defined in a different sequence, can still be compared correctly with methods equals and notEqualTo.
- There are no methods that modify an existing
HashSetHashSetHashSetHashSetHashSet, but several (e.g. add and remove)
return a new HashSetHashSetHashSetHashSetHashSet that is based on the original HashSet or HashSets with specified differences.
This enables a HashSet to work like a mathematical set so that it is possible to perform standard set operations such as union and intersection.
When creating a HashSetHashSetHashSetHashSetHashSet, the type of its members must be specified in the form
HashSet<of String>HashSet[str]HashSet<string>HashSet(Of String)HashSet<String>
You can add members: either individually with add, or many with addFromList.
And you can create a new HashSetHashSetHashSetHashSetHashSet from an existing ListlistListListList by calling asSet on it.
Example of creating a HashSetHashSetHashSetHashSetHashSet from a literal ListlistListListList and changing its content:
+main
7
variable stname? set to new HashSet<of Int>()value or expression?8
assign stvariableName? to st.addFromList([3, 5, 7])value or expression?9
print(st.length()value or expression?)10
assign stvariableName? to st.add(7)value or expression?11
assign stvariableName? to st.remove(3)value or expression?12
print(st.length()value or expression?)13
assign stvariableName? to st.remove(3)value or expression?14
print(st.length()value or expression?)15
print(stvalue or expression?)16
end main
+def main() -> None:
17
stname? = HashSet[int]()value or expression? # variable definition18
stvariableName? = st.addFromList([3, 5, 7])value or expression? # assignment19
print(st.length()value or expression?)20
stvariableName? = st.add(7)value or expression? # assignment21
stvariableName? = st.remove(3)value or expression? # assignment22
print(st.length()value or expression?)23
stvariableName? = st.remove(3)value or expression? # assignment24
print(st.length()value or expression?)25
print(stvalue or expression?)26
# end main
+static void main() {
27
var stname? = new HashSet<int>()value or expression?;28
stvariableName? = st.addFromList(new [] {3, 5, 7})value or expression?; // assignment29
Console.WriteLine(st.length()value or expression?); // print statement30
stvariableName? = st.add(7)value or expression?; // assignment31
stvariableName? = st.remove(3)value or expression?; // assignment32
Console.WriteLine(st.length()value or expression?); // print statement33
stvariableName? = st.remove(3)value or expression?; // assignment34
Console.WriteLine(st.length()value or expression?); // print statement35
Console.WriteLine(stvalue or expression?); // print statement36
} // end main
+Sub main()
37
Dim stname? = New HashSet(Of Integer)()value or expression? ' variable definition38
stvariableName? = st.addFromList({3, 5, 7})value or expression? ' assignment39
Console.WriteLine(st.length()value or expression?) ' print statement40
stvariableName? = st.add(7)value or expression? ' assignment41
stvariableName? = st.remove(3)value or expression? ' assignment42
Console.WriteLine(st.length()value or expression?) ' print statement43
stvariableName? = st.remove(3)value or expression? ' assignment44
Console.WriteLine(st.length()value or expression?) ' print statement45
Console.WriteLine(stvalue or expression?) ' print statement46
End Sub
+static void main() {
47
var stname? = new HashSet<int>()value or expression?;48
stvariableName? = st.addFromList(list(3, 5, 7))value or expression?; // assignment49
System.out.println(st.length()value or expression?); // print statement50
stvariableName? = st.add(7)value or expression?; // assignment51
stvariableName? = st.remove(3)value or expression?; // assignment52
System.out.println(st.length()value or expression?); // print statement53
stvariableName? = st.remove(3)value or expression?; // assignment54
System.out.println(st.length()value or expression?); // print statement55
System.out.println(stvalue or expression?); // print statement56
} // end main
|
⟶
⟶
⟶ ⟶
|
3
2
2 [5, 7]
|
Function dot methods on a HashSetHashSetHashSetHashSetHashSet
function dot method |
argument types |
return type |
returns |
| add |
value (of HashSetHashSetHashSetHashSetHashSet members' type) |
HashSetHashSetHashSetHashSetHashSet |
a new Set extended with the item, provided it differs from all of the Set's current members |
| addFromList |
ListlistListListList |
HashSetHashSetHashSetHashSetHashSet |
a new Set extended with those items from the ListlistListListList that are not already in the Set |
| asList |
(none) |
ListlistListListList |
a ListlistListListList containing the Set's members as ListlistListListList items |
| contains |
value (of HashSetHashSetHashSetHashSetHashSet members' type) |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if the Set contains the item – falseFalsefalseFalsefalse otherwise |
| difference |
HashSetHashSetHashSetHashSetHashSet |
HashSetHashSetHashSetHashSetHashSet |
a Set containing those members of the Set that do not occur in the argument Set |
| equals |
HashSetHashSetHashSetHashSetHashSet |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if Set and argument Set contain identical values – falseFalsefalseFalsefalse otherwise |
| notEqualTo |
HashSetHashSetHashSetHashSetHashSet |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if Set and argument Set differ in their values – falseFalsefalseFalsefalse otherwise |
| intersection |
HashSetHashSetHashSetHashSetHashSet |
HashSetHashSetHashSetHashSetHashSet |
a HashSet containing those members common to both the Set and the argument Set |
| isDisjointFrom |
HashSetHashSetHashSetHashSetHashSet |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if the Set has no items in common with the argument Set – falseFalsefalseFalsefalse otherwise |
| isSubsetOf |
HashSetHashSetHashSetHashSetHashSet |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if all the Set's items are also in the argument Set – falseFalsefalseFalsefalse otherwise |
| isSupersetOf |
HashSetHashSetHashSetHashSetHashSet |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if the Set contains all the items that are in the argument Set – falseFalsefalseFalsefalse otherwise |
| length |
(none) |
IntintintIntegerint |
the number of members of the Set |
| remove |
value (of HashSetHashSetHashSetHashSetHashSet members' type) |
HashSetHashSetHashSetHashSetHashSet |
a new Set with the argument item removed (if present) |
| toString |
(none) |
StringstrstringStringString |
a string that is a comma+space-separated ListlistListListList of the Set's members, enclosed in brackets |
| union |
HashSetHashSetHashSetHashSetHashSet |
HashSetHashSetHashSetHashSetHashSet |
a Set containing all the unique members of the Set and the argument Set (i.e. no duplicates) |
Stack and Queue
StackStackStackStackStack and QueueQueueQueueQueueQueue are similar data structures except that StackStackStackStackStack is 'LIFO' (last in, first out), while QueueQueueQueueQueueQueue is FIFO (first in, first out).
The names of the methods for adding and removing items are different, but there are also common methods.
- Both a
StackStackStackStackStack and a QueueQueueQueueQueueQueue are defined with the type of the items that they contain, similarly to how a ListlistListListList has a specified item type.
The type is specified in the form shown below e.g. Stack<of String>Stack[str]Stack<string>Stack(Of String)Stack<String>, Queue<of Int>Queue[int]Queue<int>Queue(Of Integer)Queue<int>.
- Both structures are dynamically extensible (like a
ListlistListListList). There is no need (or means) to specify a size limit
as they can continue to expand (eventually until the computer's memory limit is reached).
- The same syntax is used to specify the type if you want to pass a
StackStackStackStackStack or QueueQueueQueueQueueQueue into a function, or specify it as the return type.
- As well as standard common dot methods,
StackStackStackStackStack and QueueQueueQueueQueueQueue also both have method peek to read respectively the last in and first in item without removing it.
- There are two ways of adding and retrieving the next item in a Stack or a Queue:
- in a procedure, use procedure methods push and enqueue to add an item, and methods pop and dequeue to obtain and remove the next item,
- in a function, use dot methods: withPush and withEnqueue to add an item, and withPop and withDequeue to remove the next item.
Note that in a function you will usually need to peek the next item before applying withPop or withDequeue (both of which remove it).
Procedure method on a StackStackStackStackStack
procedure method |
argument |
action |
| push |
value of StackStackStackStackStack item's type |
the item is added to the top of the Stack |
Function dot methods on a StackStackStackStackStack
function dot method |
argument types |
return types |
returns |
| equals |
StackStackStackStackStack |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if stack and argument are identical – falseFalsefalseFalsefalse otherwise |
| notEqualTo |
StackStackStackStackStack |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if stack and argument differ – falseFalsefalseFalsefalse otherwise |
| pop |
(none) |
StackStackStackStackStack item |
the item most recently pushed onto the Stack, which is now deleted from the Stack |
| peek |
(none) |
StackStackStackStackStack item |
the item most recently pushed onto the Stack (without altering the Stack) |
| length |
(none) |
IntintintIntegerint |
the number of items in the Stack |
| toString |
(none) |
StringstrstringStringString |
a String that is a comma+space-separated list of the Stack's items, enclosed in square brackets,
the last item pushed being the first in the String |
| withPop |
(none) |
StackStackStackStackStack |
the Stack with the most recently pushed item removed |
| withPush |
StackStackStackStackStack item |
StackStackStackStackStack |
the item is added to the top of the Stack and the Stack returned |
Procedure method on a QueueQueueQueueQueueQueue
procedure method |
argument |
action |
| enqueue |
value of QueueQueueQueueQueueQueue item's type |
the item is added to the tail of the queue |
Function dot methods on a QueueQueueQueueQueueQueue
function dot method |
argument types |
return types |
returns |
| equals |
QueueQueueQueueQueueQueue |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if queue and argument are identical – falseFalsefalseFalsefalse otherwise |
| notEqualTo |
QueueQueueQueueQueueQueue |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if queue and argument differ – falseFalsefalseFalsefalse otherwise |
| dequeue |
(none) |
QueueQueueQueueQueueQueue item |
the item least recently enqueued on the Queue, which is now deleted from the Queue |
| peek |
(none) |
QueueQueueQueueQueueQueue item |
the item least recently enqueued on the Queue (without altering the Queue) |
| length |
(none) |
IntintintIntegerint |
the number of items in the Queue |
| toString |
(none) |
StringstrstringStringString |
a String that is a comma+space-separated list of the Queue's items, enclosed in square brackets,
the first item enqueued being the first in the String |
| withDequeue |
(none) |
QueueQueueQueueQueueQueue |
the Queue with the least recently enqueued item removed |
| withEnqueue |
QueueQueueQueueQueueQueue item |
QueueQueueQueueQueueQueue |
the item is added to the tail of the Queue and the Queue returned |
Examples using StackStackStackStackStack and QueueQueueQueueQueueQueue in a procedure
● Results of push and pop on strings in a StackStackStackStackStack that starts empty:
+procedure stackProcname?(sk as Stack<of String>parameter definitions?)
57
print(sk.length()value or expression?)58
call sk.pushprocedureName?("apple"arguments?)59
call sk.pushprocedureName?("banana"arguments?)60
call sk.pushprocedureName?("cherry"arguments?)61
print(sk.length()value or expression?)62
print(skvalue or expression?)63
print(sk.peek()value or expression?)64
print(skvalue or expression?)65
variable fruitname? set to sk.pop()value or expression?66
print(fruitvalue or expression?)67
print(skvalue or expression?)68
end procedure
+def stackProcname?(sk: Stack[str]parameter definitions?) -> None:
# procedure69
print(sk.length()value or expression?)70
sk.pushprocedureName?("apple"arguments?) # procedure call71
sk.pushprocedureName?("banana"arguments?) # procedure call72
sk.pushprocedureName?("cherry"arguments?) # procedure call73
print(sk.length()value or expression?)74
print(skvalue or expression?)75
print(sk.peek()value or expression?)76
print(skvalue or expression?)77
fruitname? = sk.pop()value or expression? # variable definition78
print(fruitvalue or expression?)79
print(skvalue or expression?)80
# end procedure
+static void stackProcname?(Stack<string> skparameter definitions?) {
// procedure81
Console.WriteLine(sk.length()value or expression?); // print statement82
sk.pushprocedureName?("apple"arguments?); // procedure call83
sk.pushprocedureName?("banana"arguments?); // procedure call84
sk.pushprocedureName?("cherry"arguments?); // procedure call85
Console.WriteLine(sk.length()value or expression?); // print statement86
Console.WriteLine(skvalue or expression?); // print statement87
Console.WriteLine(sk.peek()value or expression?); // print statement88
Console.WriteLine(skvalue or expression?); // print statement89
var fruitname? = sk.pop()value or expression?;90
Console.WriteLine(fruitvalue or expression?); // print statement91
Console.WriteLine(skvalue or expression?); // print statement92
} // end procedure
+Sub stackProcname?(sk As Stack(Of String)parameter definitions?)
' procedure93
Console.WriteLine(sk.length()value or expression?) ' print statement94
sk.pushprocedureName?("apple"arguments?) ' procedure call95
sk.pushprocedureName?("banana"arguments?) ' procedure call96
sk.pushprocedureName?("cherry"arguments?) ' procedure call97
Console.WriteLine(sk.length()value or expression?) ' print statement98
Console.WriteLine(skvalue or expression?) ' print statement99
Console.WriteLine(sk.peek()value or expression?) ' print statement100
Console.WriteLine(skvalue or expression?) ' print statement101
Dim fruitname? = sk.pop()value or expression? ' variable definition102
Console.WriteLine(fruitvalue or expression?) ' print statement103
Console.WriteLine(skvalue or expression?) ' print statement104
End Sub
+static void stackProcname?(Stack<String> skparameter definitions?) {
// procedure105
System.out.println(sk.length()value or expression?); // print statement106
sk.pushprocedureName?("apple"arguments?); // procedure call107
sk.pushprocedureName?("banana"arguments?); // procedure call108
sk.pushprocedureName?("cherry"arguments?); // procedure call109
System.out.println(sk.length()value or expression?); // print statement110
System.out.println(skvalue or expression?); // print statement111
System.out.println(sk.peek()value or expression?); // print statement112
System.out.println(skvalue or expression?); // print statement113
var fruitname? = sk.pop()value or expression?;114
System.out.println(fruitvalue or expression?); // print statement115
System.out.println(skvalue or expression?); // print statement116
} // end procedure
|
⟶
⟶ ⟶ ⟶ ⟶
⟶ ⟶ |
0
3 [cherry, banana, apple] — note the order of items cherry [cherry, banana, apple] — no change on peek
cherry [banana, apple] — last added item was popped |
● Results of enqueue and dequeue on strings in a QueueQueueQueueQueueQueue that starts empty:
+procedure queueProcname?(qu as Queue<of String>parameter definitions?)
117
print(qu.length()value or expression?)118
call qu.enqueueprocedureName?("apple"arguments?)119
call qu.enqueueprocedureName?("banana"arguments?)120
call qu.enqueueprocedureName?("cherry"arguments?)121
print(qu.length()value or expression?)122
print(quvalue or expression?)123
print(qu.peek()value or expression?)124
print(quvalue or expression?)125
variable fruitname? set to qu.dequeue()value or expression?126
print(fruitvalue or expression?)127
print(quvalue or expression?)128
end procedure
+def queueProcname?(qu: Queue[str]parameter definitions?) -> None:
# procedure129
print(qu.length()value or expression?)130
qu.enqueueprocedureName?("apple"arguments?) # procedure call131
qu.enqueueprocedureName?("banana"arguments?) # procedure call132
qu.enqueueprocedureName?("cherry"arguments?) # procedure call133
print(qu.length()value or expression?)134
print(quvalue or expression?)135
print(qu.peek()value or expression?)136
print(quvalue or expression?)137
fruitname? = qu.dequeue()value or expression? # variable definition138
print(fruitvalue or expression?)139
print(quvalue or expression?)140
# end procedure
+static void queueProcname?(Queue<string> quparameter definitions?) {
// procedure141
Console.WriteLine(qu.length()value or expression?); // print statement142
qu.enqueueprocedureName?("apple"arguments?); // procedure call143
qu.enqueueprocedureName?("banana"arguments?); // procedure call144
qu.enqueueprocedureName?("cherry"arguments?); // procedure call145
Console.WriteLine(qu.length()value or expression?); // print statement146
Console.WriteLine(quvalue or expression?); // print statement147
Console.WriteLine(qu.peek()value or expression?); // print statement148
Console.WriteLine(quvalue or expression?); // print statement149
var fruitname? = qu.dequeue()value or expression?;150
Console.WriteLine(fruitvalue or expression?); // print statement151
Console.WriteLine(quvalue or expression?); // print statement152
} // end procedure
+Sub queueProcname?(qu As Queue(Of String)parameter definitions?)
' procedure153
Console.WriteLine(qu.length()value or expression?) ' print statement154
qu.enqueueprocedureName?("apple"arguments?) ' procedure call155
qu.enqueueprocedureName?("banana"arguments?) ' procedure call156
qu.enqueueprocedureName?("cherry"arguments?) ' procedure call157
Console.WriteLine(qu.length()value or expression?) ' print statement158
Console.WriteLine(quvalue or expression?) ' print statement159
Console.WriteLine(qu.peek()value or expression?) ' print statement160
Console.WriteLine(quvalue or expression?) ' print statement161
Dim fruitname? = qu.dequeue()value or expression? ' variable definition162
Console.WriteLine(fruitvalue or expression?) ' print statement163
Console.WriteLine(quvalue or expression?) ' print statement164
End Sub
+static void queueProcname?(Queue<String> quparameter definitions?) {
// procedure165
System.out.println(qu.length()value or expression?); // print statement166
qu.enqueueprocedureName?("apple"arguments?); // procedure call167
qu.enqueueprocedureName?("banana"arguments?); // procedure call168
qu.enqueueprocedureName?("cherry"arguments?); // procedure call169
System.out.println(qu.length()value or expression?); // print statement170
System.out.println(quvalue or expression?); // print statement171
System.out.println(qu.peek()value or expression?); // print statement172
System.out.println(quvalue or expression?); // print statement173
var fruitname? = qu.dequeue()value or expression?;174
System.out.println(fruitvalue or expression?); // print statement175
System.out.println(quvalue or expression?); // print statement176
} // end procedure
|
⟶
⟶ ⟶ ⟶ ⟶
⟶ ⟶ |
0
3 [apple, banana, cherry] — note the order of items apple [apple, banana, cherry] — no change on peek
apple [banana, cherry] — first added item was dequeued |
Example using QueueQueueQueueQueueQueue in functions
● Adding to a QueueQueueQueueQueueQueue by function, then transforming its contents in a function (via a StringstrstringStringString, a ListlistListListList and the HoF reduce):
+main
1
variable quname? set to new Queue<of String>()value or expression?2
assign quvariableName? to quEnqueue(qu, "jones")value or expression?3
assign quvariableName? to quEnqueue(qu, "Smith")value or expression?4
assign quvariableName? to quEnqueue(qu, "JACKSON")value or expression?5
print(quvalue or expression?)6
print(quUpper(qu)value or expression?)7
end main
+function quEnqueuename?(qu as Queue<of String>, s as Stringparameter definitions?) returns Queue<of String>Type?
8
return qu.withEnqueue(s)value or expression?9
end function
+function quUppername?(qu as Queue<of String>parameter definitions?) returns Queue<of String>Type?
10
let quStringname? be qu.toString().upperCase().replace("[", "").replace("]", "")value or expression?11
let quListname? be quString.split(", ")value or expression?12
let quRname? be new Queue<of String>()value or expression?13
return quList.reduce(quR, lambda quR as Queue<of String>, s as String => quR.withEnqueue(s))value or expression?14
end function
+def main() -> None:
1
quname? = Queue[str]()value or expression? # variable definition2
quvariableName? = quEnqueue(qu, "jones")value or expression? # assignment3
quvariableName? = quEnqueue(qu, "Smith")value or expression? # assignment4
quvariableName? = quEnqueue(qu, "JACKSON")value or expression? # assignment5
print(quvalue or expression?)6
print(quUpper(qu)value or expression?)7
# end main
+def quEnqueuename?(qu: Queue[str], s: strparameter definitions?) -> Queue[str]Type?:
# function8
return qu.withEnqueue(s)value or expression?9
# end function
+def quUppername?(qu: Queue[str]parameter definitions?) -> Queue[str]Type?:
# function10
quStringname? = qu.toString().upperCase().replace("[", "").replace("]", "")value or expression? # let11
quListname? = quString.split(", ")value or expression? # let12
quRname? = Queue[str]()value or expression? # let13
return quList.reduce(quR, lambda quR: Queue[str], s: str: quR.withEnqueue(s))value or expression?14
# end function
main()
+static void main() {
1
var quname? = new Queue<string>()value or expression?;2
quvariableName? = quEnqueue(qu, "jones")value or expression?; // assignment3
quvariableName? = quEnqueue(qu, "Smith")value or expression?; // assignment4
quvariableName? = quEnqueue(qu, "JACKSON")value or expression?; // assignment5
Console.WriteLine(quvalue or expression?); // print statement6
Console.WriteLine(quUpper(qu)value or expression?); // print statement7
} // end main
+static Queue<string>Type? quEnqueuename?(Queue<string> qu, string sparameter definitions?) {
// function8
return qu.withEnqueue(s)value or expression?;9
} // end function
+static Queue<string>Type? quUppername?(Queue<string> quparameter definitions?) {
// function10
var quStringname? = qu.toString().upperCase().replace("[", "").replace("]", "")value or expression?; // let11
var quListname? = quString.split(", ")value or expression?; // let12
var quRname? = new Queue<string>()value or expression?; // let13
return quList.reduce(quR, Queue<string> quR, string s => quR.withEnqueue(s))value or expression?;14
} // end function
+Sub main()
1
Dim quname? = New Queue(Of String)()value or expression? ' variable definition2
quvariableName? = quEnqueue(qu, "jones")value or expression? ' assignment3
quvariableName? = quEnqueue(qu, "Smith")value or expression? ' assignment4
quvariableName? = quEnqueue(qu, "JACKSON")value or expression? ' assignment5
Console.WriteLine(quvalue or expression?) ' print statement6
Console.WriteLine(quUpper(qu)value or expression?) ' print statement7
End Sub
+Function quEnqueuename?(qu As Queue(Of String), s As Stringparameter definitions?) As Queue(Of String)Type?
8
Return qu.withEnqueue(s)value or expression?9
End Function
+Function quUppername?(qu As Queue(Of String)parameter definitions?) As Queue(Of String)Type?
10
Dim quStringname? = qu.toString().upperCase().replace("(", "").replace(")", "")value or expression? ' let11
Dim quListname? = quString.split(", ")value or expression? ' let12
Dim quRname? = New Queue(Of String)()value or expression? ' let13
Return quList.reduce(quR, Function (quR As Queue(Of String), s As String) quR.withEnqueue(s))value or expression?14
End Function
public class Global {
+static void main() {
1
var quname? = new Queue<String>()value or expression?;2
quvariableName? = quEnqueue(qu, "jones")value or expression?; // assignment3
quvariableName? = quEnqueue(qu, "Smith")value or expression?; // assignment4
quvariableName? = quEnqueue(qu, "JACKSON")value or expression?; // assignment5
System.out.println(quvalue or expression?); // print statement6
System.out.println(quUpper(qu)value or expression?); // print statement7
} // end main
+static Queue<String>Type? quEnqueuename?(Queue<String> qu, String sparameter definitions?) {
// function8
return qu.withEnqueue(s)value or expression?;9
} // end function
+static Queue<String>Type? quUppername?(Queue<String> quparameter definitions?) {
// function10
var quStringname? = qu.toString().upperCase().replace("[", "").replace("]", "")value or expression?; // let11
var quListname? = quString.split(", ")value or expression?; // let12
var quRname? = new Queue<String>()value or expression?; // let13
return quList.reduce(quR, (Queue<String> quR, String s) -> quR.withEnqueue(s))value or expression?;14
} // end function
} // end Global
|
⟶ ⟶ |
[jones, Smith, JACKSON] [JONES, SMITH, JACKSON] |
Tuple
A Tuple is not a value or data structure type. Rather, it is a small collection of values
of differing types held together and referenced by a single identifier.
It may be considered a lightweight alternative to defining a class for some specific purpose.
The items in a Tuple may be literal or named values.
Tuples are referred to as 2-tuples, 3-tuples, etc. according to the number of values they hold.
An item within a Tuple may be another Tuple, giving nested Tuples.
A function may return a Tuple.
A Tuple differs from a ListlistListListList in that:
- A Tuple may hold items of different types.
- A Tuple is immutable: you may read, but not modify, the values it contains.
Once defined, Tuples are effectively read-only.
Nor, unlike a ListlistListListList, can you copy a Tuple
from an existing one with specified differences except by referencing each of its items (see below).
Common uses include:
- Holding a pair of x,y coordinates (each of type
FloatfloatdoubleDoubledouble) as a single unit.
- Allowing a function to pass back a result comprised of both a message in a
StringstrstringStringString and a BooleanboolboolBooleanboolean indicating whether the operation was successful.
Defining a Tuple
A new Tuple is defined by a list of items separated by commas and enclosed in round brackets:
variable pointname? set to (3, 4)value or expression?31pointname? = (3, 4)value or expression? # variable definition32var pointname? = (3, 4)value or expression?;33Dim pointname? = (3, 4)value or expression? ' variable definition34var pointname? = (3, 4)value or expression?;35
variable tname? set to (3, "apple", true)value or expression?36tname? = (3, "apple", True)value or expression? # variable definition37var tname? = (3, "apple", true)value or expression?;38Dim tname? = (3, "apple", True)value or expression? ' variable definition39var tname? = (3, "apple", true)value or expression?;40
Accessing items in a Tuple
The items in a Tuple may be individually addressed by a dot reference and the special properties item_item_item_item_item_N, thus:
+main
15
variable tname? set to (3, "apple", true)value or expression?16
print(tvalue or expression?)17
print(t.item_0value or expression?)18
print(t.item_1value or expression?)19
print(t.item_2value or expression?)20
end main
+def main() -> None:
21
tname? = (3, "apple", True)value or expression? # variable definition22
print(tvalue or expression?)23
print(t.item_0value or expression?)24
print(t.item_1value or expression?)25
print(t.item_2value or expression?)26
# end main
+static void main() {
27
var tname? = (3, "apple", true)value or expression?;28
Console.WriteLine(tvalue or expression?); // print statement29
Console.WriteLine(t.item_0value or expression?); // print statement30
Console.WriteLine(t.item_1value or expression?); // print statement31
Console.WriteLine(t.item_2value or expression?); // print statement32
} // end main
+Sub main()
33
Dim tname? = (3, "apple", True)value or expression? ' variable definition34
Console.WriteLine(tvalue or expression?) ' print statement35
Console.WriteLine(t.item_0value or expression?) ' print statement36
Console.WriteLine(t.item_1value or expression?) ' print statement37
Console.WriteLine(t.item_2value or expression?) ' print statement38
End Sub
+static void main() {
39
var tname? = (3, "apple", true)value or expression?;40
System.out.println(tvalue or expression?); // print statement41
System.out.println(t.item_0value or expression?); // print statement42
System.out.println(t.item_1value or expression?); // print statement43
System.out.println(t.item_2value or expression?); // print statement44
} // end main
|
⟶ ⟶ ⟶ ⟶ |
(3, apple, true) 3 apple true |
And where p1 and p2 represent points each with 2-tuples containing two FloatfloatdoubleDoubledouble values, this function returns the distance between them:
+function distanceBetweenname?(p1 as (Float, Float), p2 as (Float, Float)parameter definitions?) returns FloatType?
45
return sqrt(pow(p2.item_0 - p1.item_0, 2) + pow(p2.item_1 - p1.item_1, 2))value or expression?46
end function
+def distanceBetweenname?(p1: tuple[float, float], p2: tuple[float, float]parameter definitions?) -> floatType?:
# function47
return sqrt(pow(p2.item_0 - p1.item_0, 2) + pow(p2.item_1 - p1.item_1, 2))value or expression?48
# end function
+static doubleType? distanceBetweenname?((double, double) p1, (double, double) p2parameter definitions?) {
// function49
return sqrt(pow(p2.item_0 - p1.item_0, 2) + pow(p2.item_1 - p1.item_1, 2))value or expression?;50
} // end function
+Function distanceBetweenname?(p1 As (Double, Double), p2 As (Double, Double)parameter definitions?) As DoubleType?
51
Return sqrt(pow(p2.item_0 - p1.item_0, 2) + pow(p2.item_1 - p1.item_1, 2))value or expression?52
End Function
+static doubleType? distanceBetweenname?((double, double) p1, (double, double) p2parameter definitions?) {
// function53
return sqrt(pow(p2.item_0 - p1.item_0, 2) + pow(p2.item_1 - p1.item_1, 2))value or expression?;54
} // end function
Note that the appropriate item_item_item_item_item_Ns will be listed in the Editor's drop-down menu options for the referenced Tuple.
Function dot methods on a Tuple
function dot methods |
argument types |
return type |
returns |
| equals |
Tuple |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if the types, item values and order all equal those of the argument, – falseFalsefalseFalsefalse otherwise |
| notEqualTo |
Tuple |
BooleanboolboolBooleanboolean |
trueTruetrueTruetrue if any of the types, item values and order differ from those of the argument, – falseFalsefalseFalsefalse otherwise |
| toString |
(none) |
StringstrstringStringString |
String containing Tuple's items surrounded by brackets |
Graphic types
Block graphics
Block graphics provides a simple way to create low resolution graphics, ideal for simple but engaging games for example.
The graphics are defined and displayed on a grid that is 40 blocks wide by 30 blocks high.
Each block is be rendered as a solid colour.
An example of block graphics to produce a rapidly changing pattern of coloured blocks:
+main
55
variable gridname? set to createBlockGraphics(white)value or expression?56
+while truecondition?
57
variable xname? set to randint(0, 39)value or expression?58
variable yname? set to randint(0, 29)value or expression?59
variable colourname? set to randint(0, white - 1)value or expression?60
assign grid[x][y]variableName? to colourvalue or expression?61
call displayBlocksprocedureName?(gridarguments?)62
end while
end main
+def main() -> None:
63
gridname? = createBlockGraphics(white)value or expression? # variable definition64
+while Truecondition?:
65
xname? = randint(0, 39)value or expression? # variable definition66
yname? = randint(0, 29)value or expression? # variable definition67
colourname? = randint(0, white - 1)value or expression? # variable definition68
grid[x][y]variableName? = colourvalue or expression? # assignment69
displayBlocksprocedureName?(gridarguments?) # procedure call70
# end while
# end main
+static void main() {
71
var gridname? = createBlockGraphics(white)value or expression?;72
+while (truecondition?) {
73
var xname? = randint(0, 39)value or expression?;74
var yname? = randint(0, 29)value or expression?;75
var colourname? = randint(0, white - 1)value or expression?;76
grid[x][y]variableName? = colourvalue or expression?; // assignment77
displayBlocksprocedureName?(gridarguments?); // procedure call78
} // end while
} // end main
+Sub main()
79
Dim gridname? = createBlockGraphics(white)value or expression? ' variable definition80
+While Truecondition?
81
Dim xname? = randint(0, 39)value or expression? ' variable definition82
Dim yname? = randint(0, 29)value or expression? ' variable definition83
Dim colourname? = randint(0, white - 1)value or expression? ' variable definition84
grid(x)(y)variableName? = colourvalue or expression? ' assignment85
displayBlocksprocedureName?(gridarguments?) ' procedure call86
End While
End Sub
+static void main() {
87
var gridname? = createBlockGraphics(white)value or expression?;88
+while (truecondition?) {
89
var xname? = randint(0, 39)value or expression?;90
var yname? = randint(0, 29)value or expression?;91
var colourname? = randint(0, white - 1)value or expression?;92
grid[x][y]variableName? = colourvalue or expression?; // assignment93
displayBlocksprocedureName?(gridarguments?); // procedure call94
} // end while
} // end main
Notes
- The definition of the grid is made using the library function createBlockGraphics which initialises
a
List<of List<of Int>>list[list[int]]List<List<int>>List(Of List(Of Integer))List<List<int>> structure
containing 40 columns × 30 rows.
- Each cell of the grid is referenced by integers x,y where x is in [0..39] and y is in [0..29].
- x,y is 0,0 at the top left cell of the grid, positive x to the right, positive y downwards.
- You may create multiple such structures holding different patterns of blocks, and switch between them
just by passing the required one as the argument to method displayBlocks.
- Any
List<of List<of Int>>list[list[int]]List<List<int>>List(Of List(Of Integer))List<List<int>> structure of the same
40 × 30 dimensions can be the argument to method displayBlocks.
- A colour is specified as an
IntintintIntegerint, as described under Colours .
Turtle graphics
Turtle graphics are implemented with output to the IDE's display pane, i.e. the 'paper' on which the turtle draws.
The area is 200 turtle units wide by 150 turtle units high, and both integer and floating point values of turtle units can be used.
If a turtle is placed or moved outside the 200 × 150 area boundary, it will not cause an error,
but the turtle and any lines drawn outside the boundary will not be visible.
The origin for turtle units (0,0) is at the centre of the area: positive x rightwards, positive y upwards.
So the top left corner of the display is at (-100,75).
A new turtle's default starting position is at (0,0) facing upwards (headingheadingheadingheadingheading is 0), from where a move will be in the y direction.
You can move and turn a turtle, causing lines to be drawn, whether or not the turtle is showing.
Procedure methods on a Turtle
procedure method |
argument types |
action |
| clearAndReset |
(none) |
clears the turtle display and moves the turtle to its starting position and heading |
| hide |
(none) |
makes the turtle invisible in the display |
| move |
IntintintIntegerint or FloatfloatdoubleDoubledouble |
moves the turtle the specified number of turtle units in the direction of its heading or, if negative, in the opposite direction |
| moveTo |
IntintintIntegerint or FloatfloatdoubleDoubledouble,
IntintintIntegerint or FloatfloatdoubleDoubledouble |
moves the turtle to the specified x,y position, drawing its path if its pen is down |
| penColour |
IntintintIntegerint |
changes the colour of its path in the display to the literal or named value specified |
| penDown |
(none) |
makes the turtle's subsequent moves leave a trace of its path in the display |
| penUp |
(none) |
makes the turtle's subsequent moves leave no trace of its path in the display |
| penWidth |
IntintintIntegerint or FloatfloatdoubleDoubledouble |
changes the width of the line tracing the turtle's path in the display default (and minimum) is 1 |
| placeAt |
IntintintIntegerint or FloatfloatdoubleDoubledouble,
IntintintIntegerint or FloatfloatdoubleDoubledouble |
places or repositions the turtle at the x,y position specified without drawing a path |
| show |
(none) |
makes the turtle visible in the display as a green blob marked with a black radius that indicates its heading |
| turn |
IntintintIntegerint or FloatfloatdoubleDoubledouble |
turns the turtle through the specified number of degrees clockwise or, if negative, anticlockwise |
| turnToHeading |
IntintintIntegerint or FloatfloatdoubleDoubledouble |
turns the turtle to face in the direction specified in degrees where 0 is upward and increasing values go clockwise from there |
Properties of a Turtle
The current location and heading of the turtle may be read using the properties
xxxxx, yyyyy, and headingheadingheadingheadingheading.
| Property |
|
| name |
type |
description |
default |
headingheadingheadingheadingheading |
FloatfloatdoubleDoubledouble |
the direction in which the turtle is pointing in degrees clockwise from North |
0.0 degrees, i.e. upward in the display |
xxxxx, yyyyy |
FloatfloatdoubleDoubledouble, FloatfloatdoubleDoubledouble |
the x,y coordinates of the turtle's current position |
0.0, 0.0 |
Examples using turtle graphics
● To draw a square:
+main
95
variable tname? set to new Turtle()value or expression?96
call t.placeAtprocedureName?(-75, 50arguments?)97
call t.showprocedureName?(arguments?)98
+for iitem? in range(1, 5)source?
99
call t.turnprocedureName?(90arguments?)100
call t.moveprocedureName?(80arguments?)101
call sleepprocedureName?(0.5arguments?)102
end for
end main
+def main() -> None:
103
tname? = Turtle()value or expression? # variable definition104
t.placeAtprocedureName?(-75, 50arguments?) # procedure call105
t.showprocedureName?(arguments?) # procedure call106
+for iitem? in range(1, 5)source?:
107
t.turnprocedureName?(90arguments?) # procedure call108
t.moveprocedureName?(80arguments?) # procedure call109
sleepprocedureName?(0.5arguments?) # procedure call110
# end for
# end main
+static void main() {
111
var tname? = new Turtle()value or expression?;112
t.placeAtprocedureName?(-75, 50arguments?); // procedure call113
t.showprocedureName?(arguments?); // procedure call114
+foreach (var iitem? in range(1, 5)source?) {
115
t.turnprocedureName?(90arguments?); // procedure call116
t.moveprocedureName?(80arguments?); // procedure call117
sleepprocedureName?(0.5arguments?); // procedure call118
} // end foreach
} // end main
+Sub main()
119
Dim tname? = New Turtle()value or expression? ' variable definition120
t.placeAtprocedureName?(-75, 50arguments?) ' procedure call121
t.showprocedureName?(arguments?) ' procedure call122
+For Each iitem? In range(1, 5)source?
123
t.turnprocedureName?(90arguments?) ' procedure call124
t.moveprocedureName?(80arguments?) ' procedure call125
sleepprocedureName?(0.5arguments?) ' procedure call126
Next i
End Sub
+static void main() {
127
var tname? = new Turtle()value or expression?;128
t.placeAtprocedureName?(-75, 50arguments?); // procedure call129
t.showprocedureName?(arguments?); // procedure call130
+foreach (var iitem? in range(1, 5)source?) {
131
t.turnprocedureName?(90arguments?); // procedure call132
t.moveprocedureName?(80arguments?); // procedure call133
sleepprocedureName?(0.5arguments?); // procedure call134
} // end foreach
} // end main

● To draw a fractal snowflake, using a procedure and recursion:
+main
1
variable tname? set to new Turtle()value or expression?2
call t.placeAtprocedureName?(-50, 30arguments?)3
call t.turnprocedureName?(90arguments?)4
call t.showprocedureName?(arguments?)5
+for iitem? in range(1, 4)source?
6
call drawSideprocedureName?(side, targuments?)7
call t.turnprocedureName?(120arguments?)8
end for
end main
+constant sidename? set to 100literal value or data structure?9
+procedure drawSidename?(length as Float, t as Turtleparameter definitions?)
10
+if (length > 1)condition? then
11
variable thirdname? set to length/3value or expression?12
call drawSideprocedureName?(third, targuments?)13
call t.turnprocedureName?(-60arguments?)14
call drawSideprocedureName?(third, targuments?)15
call t.turnprocedureName?(120arguments?)16
call drawSideprocedureName?(third, targuments?)17
call t.turnprocedureName?(-60arguments?)18
call drawSideprocedureName?(third, targuments?)19
else20
call t.moveprocedureName?(lengtharguments?)21
end if
end procedure
+def main() -> None:
1
tname? = Turtle()value or expression? # variable definition2
t.placeAtprocedureName?(-50, 30arguments?) # procedure call3
t.turnprocedureName?(90arguments?) # procedure call4
t.showprocedureName?(arguments?) # procedure call5
+for iitem? in range(1, 4)source?:
6
drawSideprocedureName?(side, targuments?) # procedure call7
t.turnprocedureName?(120arguments?) # procedure call8
# end for
# end main
+sidename? = 100literal value or data structure? # constant9
+def drawSidename?(length: float, t: Turtleparameter definitions?) -> None:
# procedure10
+if (length > 1)condition?:
11
thirdname? = length/3value or expression? # variable definition12
drawSideprocedureName?(third, targuments?) # procedure call13
t.turnprocedureName?(-60arguments?) # procedure call14
drawSideprocedureName?(third, targuments?) # procedure call15
t.turnprocedureName?(120arguments?) # procedure call16
drawSideprocedureName?(third, targuments?) # procedure call17
t.turnprocedureName?(-60arguments?) # procedure call18
drawSideprocedureName?(third, targuments?) # procedure call19
else:20
t.moveprocedureName?(lengtharguments?) # procedure call21
# end if
# end procedure
main()
+static void main() {
1
var tname? = new Turtle()value or expression?;2
t.placeAtprocedureName?(-50, 30arguments?); // procedure call3
t.turnprocedureName?(90arguments?); // procedure call4
t.showprocedureName?(arguments?); // procedure call5
+foreach (var iitem? in range(1, 4)source?) {
6
drawSideprocedureName?(side, targuments?); // procedure call7
t.turnprocedureName?(120arguments?); // procedure call8
} // end foreach
} // end main
+const Int sidename? = 100literal value or data structure?;9
+static void drawSidename?(double length, Turtle tparameter definitions?) {
// procedure10
+if ((length > 1)condition?) {
11
var thirdname? = length/3value or expression?;12
drawSideprocedureName?(third, targuments?); // procedure call13
t.turnprocedureName?(-60arguments?); // procedure call14
drawSideprocedureName?(third, targuments?); // procedure call15
t.turnprocedureName?(120arguments?); // procedure call16
drawSideprocedureName?(third, targuments?); // procedure call17
t.turnprocedureName?(-60arguments?); // procedure call18
drawSideprocedureName?(third, targuments?); // procedure call19
} else {20
t.moveprocedureName?(lengtharguments?); // procedure call21
} // end if
} // end procedure
+Sub main()
1
Dim tname? = New Turtle()value or expression? ' variable definition2
t.placeAtprocedureName?(-50, 30arguments?) ' procedure call3
t.turnprocedureName?(90arguments?) ' procedure call4
t.showprocedureName?(arguments?) ' procedure call5
+For Each iitem? In range(1, 4)source?
6
drawSideprocedureName?(side, targuments?) ' procedure call7
t.turnprocedureName?(120arguments?) ' procedure call8
Next i
End Sub
+Const sidename? = 100literal value or data structure?9
+Sub drawSidename?(length As Double, t As Turtleparameter definitions?)
' procedure10
+If (length > 1)condition? Then
11
Dim thirdname? = length/3value or expression? ' variable definition12
drawSideprocedureName?(third, targuments?) ' procedure call13
t.turnprocedureName?(-60arguments?) ' procedure call14
drawSideprocedureName?(third, targuments?) ' procedure call15
t.turnprocedureName?(120arguments?) ' procedure call16
drawSideprocedureName?(third, targuments?) ' procedure call17
t.turnprocedureName?(-60arguments?) ' procedure call18
drawSideprocedureName?(third, targuments?) ' procedure call19
Else20
t.moveprocedureName?(lengtharguments?) ' procedure call21
End If
End Sub
public class Global {
+static void main() {
1
var tname? = new Turtle()value or expression?;2
t.placeAtprocedureName?(-50, 30arguments?); // procedure call3
t.turnprocedureName?(90arguments?); // procedure call4
t.showprocedureName?(arguments?); // procedure call5
+foreach (var iitem? in range(1, 4)source?) {
6
drawSideprocedureName?(side, targuments?); // procedure call7
t.turnprocedureName?(120arguments?); // procedure call8
} // end foreach
} // end main
+static final Int sidename? = 100literal value or data structure?; // constant9
+static void drawSidename?(double length, Turtle tparameter definitions?) {
// procedure10
+if ((length > 1)condition?) {
11
var thirdname? = length/3value or expression?;12
drawSideprocedureName?(third, targuments?); // procedure call13
t.turnprocedureName?(-60arguments?); // procedure call14
drawSideprocedureName?(third, targuments?); // procedure call15
t.turnprocedureName?(120arguments?); // procedure call16
drawSideprocedureName?(third, targuments?); // procedure call17
t.turnprocedureName?(-60arguments?); // procedure call18
drawSideprocedureName?(third, targuments?); // procedure call19
} else {20
t.moveprocedureName?(lengtharguments?); // procedure call21
} // end if
} // end procedure
}
// end Global

Vector graphics
Vector graphics are implemented using the SVG (Scalable Vector Graphics) Html tag <svg>, and are output to the display pane in the user interface.
The area is 100 units wide by 75 units high, and both integer and floating point values of the units can be used.
The origin of the units (0,0) is at the top left corner of the display: positive x rightwards, positive y downwards.
So for example the centre of the display is at (50, 37.5).
The names of the shapes broadly correspond to the names of SVG tags:
-
CircleVGCircleVGCircleVGCircleVGCircleVG for <circle../>
ImageVGImageVGImageVGImageVGImageVG for <image../>
LineVGLineVGLineVGLineVGLineVG for <line../>
RectangleVGRectangleVGRectangleVGRectangleVGRectangleVG for <rect../>
The properties of these shapes are named to reflect the attributes used in the SVG tags but some names differ. For example, SVG's stroke-width
is assigned with property strokeWidthstrokeWidthstrokeWidthstrokeWidthstrokeWidth, to make it a valid identifier .
Also strokestrokestrokestrokestroke and fillfillfillfillfill are set by the properties strokeColourstrokeColourstrokeColourstrokeColourstrokeColour and fillColourfillColourfillColourfillColourfillColour.
In addition, graphics may be displayed from any valid string of SVG tags, as described in RawVGRawVGRawVGRawVGRawVG .
Defining Vector graphic shapes
A set of SVG shapes is defined in either a List<of VectorGraphic>list[VectorGraphic]List<VectorGraphic>List(Of VectorGraphic)List<VectorGraphic> or a ListlistListListList of any specific type of VectorGraphicVectorGraphicVectorGraphicVectorGraphicVectorGraphic
(e.g. List<of CircleVG>list[CircleVG]List<CircleVG>List(Of CircleVG)List<CircleVG>) by using the ListlistListListList append method.
createVectorGraphics is a convenience method that returns an empty List<of VectorGraphic>list[VectorGraphic]List<VectorGraphic>List(Of VectorGraphic)List<VectorGraphic>
VectorGraphicVectorGraphicVectorGraphicVectorGraphicVectorGraphic is the abstract superclass of all ..VG shapes. You use it when you want to define a ListlistListListList holding different types of shape.
Adding a shape returns a new instance of the ListlistListListList which must be assigned to a new or existing variable.
The constructors for the VG types require arguments defining the attributes of the relevant SVG tags, so defaults are supplied from the class properties,
as shown in the table below.
To change the value of property 'p..', call the setP.. procedure method on the vector graphic or,
in a function, use the withP.. dot method on the vector graphic, in either case specifying new values in the arguments.
The fillColourfillColourfillColourfillColourfillColour and strokeColourstrokeColourstrokeColourstrokeColourstrokeColour properties may be specified as described under Colours .
Only fillColourfillColourfillColourfillColourfillColour can be specified as transparenttransparenttransparenttransparenttransparent.
Note that the heightheightheightheightheight and widthwidthwidthwidthwidth properties of an image are also dependent on the dimensions of the original graphic file.
Displaying Vector graphic shapes
As with Block graphics, the assembled ListlistListListList of shapes is not displayed until call procedure displayVectorGraphics with the ListlistListListList as its argument, thus allowing you to make multiple changes before display.
And as with using SVG in Html, the shapes are drawn in the order in which they are added to the VectorGraphicVectorGraphicVectorGraphicVectorGraphicVectorGraphic instance.
Later shapes are positioned in front of earlier ones.
Function dot methods on Vector graphic shapes
function dot method |
on type |
argument types |
return type |
returns |
| asHtml |
ImageVGImageVGImageVGImageVGImageVG |
none |
StringstrstringStringString |
string containing the Html <img> tag filled with the image's URL and attribute values |
| asSVG |
CircleVGCircleVGCircleVGCircleVGCircleVG |
none |
StringstrstringStringString |
string containing the SVG <circle> tag filled with the circle's attribute values |
| asSVG |
ImageVGImageVGImageVGImageVGImageVG |
none |
StringstrstringStringString |
string containing the SVG <image> tag filled with the image's URL and attribute values |
| asSVG |
LineVGLineVGLineVGLineVGLineVG |
none |
StringstrstringStringString |
string containing the SVG <line> tag filled with the line's attribute values |
| asSVG |
RectangleVGRectangleVGRectangleVGRectangleVGRectangleVG |
none |
StringstrstringStringString |
string containing the SVG <rectangle> tag filled with the rectangle's attribute values |
Properties of Vector graphic shapes
This table lists the properties of the Vector graphic shapes and their default values,
together with the procedure and function methods provided to alter their values in a given instance.
| Property |
Vector graphic shape |
Property |
Method |
| name |
type |
CircleVG |
ImageVG |
LineVG |
RectangleVG |
description |
default |
procedure |
function |
altaltaltaltalt |
StringstrstringStringString |
|
✔ |
|
|
alternate textual description (for accessibility) |
empty string |
setAlt |
withAlt |
centreXcentreXcentreXcentreXcentreX |
FloatfloatdoubleDoubledouble |
✔ |
|
|
|
horizontal position of circle centre |
50 |
setCentreX |
withCentreX |
centreYcentreYcentreYcentreYcentreY |
FloatfloatdoubleDoubledouble |
✔ |
|
|
|
vertical position of circle centre |
37.5 |
setCentreY |
withCentreY |
fillColourfillColourfillColourfillColourfillColour |
IntintintIntegerint |
✔ |
|
|
✔ |
colour to fill the shape |
yellowyellowyellowyellowyellow |
setFillColour |
withFillColour |
heightheightheightheightheight |
FloatfloatdoubleDoubledouble |
|
✔ |
|
✔ |
height to render the shape or the image |
Image: 13.2 Rectangle: 20 |
setHeight |
withHeight |
radiusradiusradiusradiusradius |
FloatfloatdoubleDoubledouble |
✔ |
|
|
|
radius of circle |
10 |
setRadius |
withRadius |
strokeColourstrokeColourstrokeColourstrokeColourstrokeColour |
IntintintIntegerint |
✔ |
|
✔ |
✔ |
colour of the strokes in the shape |
blackblackblackblackblack |
setStrokeColour |
withStrokeColour |
strokeWidthstrokeWidthstrokeWidthstrokeWidthstrokeWidth |
IntintintIntegerint |
✔ |
|
✔ |
✔ |
width of the strokes in the shape |
1 |
setStrokeWidth |
withStrokeWidth |
titletitletitletitletitle |
FloatfloatdoubleDoubledouble |
|
✔ |
|
|
title text |
empty string |
setTitle |
withTitle |
widthwidthwidthwidthwidth |
FloatfloatdoubleDoubledouble |
|
✔ |
|
✔ |
width to render the shape or the image |
Image: 13.2 Rectangle: 40 |
setWidth |
withWidth |
xxxxx, yyyyy |
FloatfloatdoubleDoubledouble, FloatfloatdoubleDoubledouble |
|
✔ ✔ |
|
✔ ✔ |
image's x,y position from top left |
Image: 0, 0 Rectangle: 10, 10 |
setX, setY |
withX, withY |
x1x1x1x1x1, y1y1y1y1y1 |
FloatfloatdoubleDoubledouble, FloatfloatdoubleDoubledouble |
|
|
✔ ✔ |
|
line's starting x,y position from top left |
10, 10 |
setX1, setY1 |
withX1, withY1 |
x2x2x2x2x2, y2y2y2y2y2 |
FloatfloatdoubleDoubledouble, FloatfloatdoubleDoubledouble |
|
|
✔ ✔ |
|
line's ending x,y position from top left |
70, 40 |
setX2, setY2 |
withX2, withY2 |
Examples using simple vector graphics
● To draw a circle with a coloured circumference:
+main
22
variable vgname? set to createVectorGraphics()value or expression?23
variable circname? set to new CircleVG()value or expression?24
call circ.setCentreXprocedureName?(20arguments?)25
call circ.setCentreYprocedureName?(20arguments?)26
call circ.setRadiusprocedureName?(5arguments?)27
call circ.setFillColourprocedureName?(greenarguments?)28
call circ.setStrokeColourprocedureName?(redarguments?)29
call circ.setStrokeWidthprocedureName?(2arguments?)30
call vg.appendprocedureName?(circarguments?)31
call displayVectorGraphicsprocedureName?(vgarguments?)32
end main
+def main() -> None:
33
vgname? = createVectorGraphics()value or expression? # variable definition34
circname? = CircleVG()value or expression? # variable definition35
circ.setCentreXprocedureName?(20arguments?) # procedure call36
circ.setCentreYprocedureName?(20arguments?) # procedure call37
circ.setRadiusprocedureName?(5arguments?) # procedure call38
circ.setFillColourprocedureName?(greenarguments?) # procedure call39
circ.setStrokeColourprocedureName?(redarguments?) # procedure call40
circ.setStrokeWidthprocedureName?(2arguments?) # procedure call41
vg.appendprocedureName?(circarguments?) # procedure call42
displayVectorGraphicsprocedureName?(vgarguments?) # procedure call43
# end main
+static void main() {
44
var vgname? = createVectorGraphics()value or expression?;45
var circname? = new CircleVG()value or expression?;46
circ.setCentreXprocedureName?(20arguments?); // procedure call47
circ.setCentreYprocedureName?(20arguments?); // procedure call48
circ.setRadiusprocedureName?(5arguments?); // procedure call49
circ.setFillColourprocedureName?(greenarguments?); // procedure call50
circ.setStrokeColourprocedureName?(redarguments?); // procedure call51
circ.setStrokeWidthprocedureName?(2arguments?); // procedure call52
vg.appendprocedureName?(circarguments?); // procedure call53
displayVectorGraphicsprocedureName?(vgarguments?); // procedure call54
} // end main
+Sub main()
55
Dim vgname? = createVectorGraphics()value or expression? ' variable definition56
Dim circname? = New CircleVG()value or expression? ' variable definition57
circ.setCentreXprocedureName?(20arguments?) ' procedure call58
circ.setCentreYprocedureName?(20arguments?) ' procedure call59
circ.setRadiusprocedureName?(5arguments?) ' procedure call60
circ.setFillColourprocedureName?(greenarguments?) ' procedure call61
circ.setStrokeColourprocedureName?(redarguments?) ' procedure call62
circ.setStrokeWidthprocedureName?(2arguments?) ' procedure call63
vg.appendprocedureName?(circarguments?) ' procedure call64
displayVectorGraphicsprocedureName?(vgarguments?) ' procedure call65
End Sub
+static void main() {
66
var vgname? = createVectorGraphics()value or expression?;67
var circname? = new CircleVG()value or expression?;68
circ.setCentreXprocedureName?(20arguments?); // procedure call69
circ.setCentreYprocedureName?(20arguments?); // procedure call70
circ.setRadiusprocedureName?(5arguments?); // procedure call71
circ.setFillColourprocedureName?(greenarguments?); // procedure call72
circ.setStrokeColourprocedureName?(redarguments?); // procedure call73
circ.setStrokeWidthprocedureName?(2arguments?); // procedure call74
vg.appendprocedureName?(circarguments?); // procedure call75
displayVectorGraphicsprocedureName?(vgarguments?); // procedure call76
} // end main

● To draw a circle that changes between red and green every second:
+main
77
variable vgname? set to new List<of VectorGraphic>()value or expression?78
variable circname? set to new CircleVG()value or expression?79
call circ.setCentreXprocedureName?(50arguments?)80
call circ.setCentreYprocedureName?(37.5arguments?)81
call circ.setRadiusprocedureName?(30arguments?)82
call circ.setFillColourprocedureName?(greenarguments?)83
call vg.appendprocedureName?(circarguments?)84
+while truecondition?
85
call displayVectorGraphicsprocedureName?(vgarguments?)86
call sleepprocedureName?(1arguments?)87
call circ.setFillColourprocedureName?(redarguments?)88
call displayVectorGraphicsprocedureName?(vgarguments?)89
call sleepprocedureName?(1arguments?)90
call circ.setFillColourprocedureName?(greenarguments?)91
end while
call displayVectorGraphicsprocedureName?(vgarguments?)92
end main
+def main() -> None:
93
vgname? = list[VectorGraphic]()value or expression? # variable definition94
circname? = CircleVG()value or expression? # variable definition95
circ.setCentreXprocedureName?(50arguments?) # procedure call96
circ.setCentreYprocedureName?(37.5arguments?) # procedure call97
circ.setRadiusprocedureName?(30arguments?) # procedure call98
circ.setFillColourprocedureName?(greenarguments?) # procedure call99
vg.appendprocedureName?(circarguments?) # procedure call100
+while Truecondition?:
101
displayVectorGraphicsprocedureName?(vgarguments?) # procedure call102
sleepprocedureName?(1arguments?) # procedure call103
circ.setFillColourprocedureName?(redarguments?) # procedure call104
displayVectorGraphicsprocedureName?(vgarguments?) # procedure call105
sleepprocedureName?(1arguments?) # procedure call106
circ.setFillColourprocedureName?(greenarguments?) # procedure call107
# end while
displayVectorGraphicsprocedureName?(vgarguments?) # procedure call108
# end main
+static void main() {
109
var vgname? = new List<VectorGraphic>()value or expression?;110
var circname? = new CircleVG()value or expression?;111
circ.setCentreXprocedureName?(50arguments?); // procedure call112
circ.setCentreYprocedureName?(37.5arguments?); // procedure call113
circ.setRadiusprocedureName?(30arguments?); // procedure call114
circ.setFillColourprocedureName?(greenarguments?); // procedure call115
vg.appendprocedureName?(circarguments?); // procedure call116
+while (truecondition?) {
117
displayVectorGraphicsprocedureName?(vgarguments?); // procedure call118
sleepprocedureName?(1arguments?); // procedure call119
circ.setFillColourprocedureName?(redarguments?); // procedure call120
displayVectorGraphicsprocedureName?(vgarguments?); // procedure call121
sleepprocedureName?(1arguments?); // procedure call122
circ.setFillColourprocedureName?(greenarguments?); // procedure call123
} // end while
displayVectorGraphicsprocedureName?(vgarguments?); // procedure call124
} // end main
+Sub main()
125
Dim vgname? = New List(Of VectorGraphic)()value or expression? ' variable definition126
Dim circname? = New CircleVG()value or expression? ' variable definition127
circ.setCentreXprocedureName?(50arguments?) ' procedure call128
circ.setCentreYprocedureName?(37.5arguments?) ' procedure call129
circ.setRadiusprocedureName?(30arguments?) ' procedure call130
circ.setFillColourprocedureName?(greenarguments?) ' procedure call131
vg.appendprocedureName?(circarguments?) ' procedure call132
+While Truecondition?
133
displayVectorGraphicsprocedureName?(vgarguments?) ' procedure call134
sleepprocedureName?(1arguments?) ' procedure call135
circ.setFillColourprocedureName?(redarguments?) ' procedure call136
displayVectorGraphicsprocedureName?(vgarguments?) ' procedure call137
sleepprocedureName?(1arguments?) ' procedure call138
circ.setFillColourprocedureName?(greenarguments?) ' procedure call139
End While
displayVectorGraphicsprocedureName?(vgarguments?) ' procedure call140
End Sub
+static void main() {
141
var vgname? = new List<VectorGraphic>()value or expression?;142
var circname? = new CircleVG()value or expression?;143
circ.setCentreXprocedureName?(50arguments?); // procedure call144
circ.setCentreYprocedureName?(37.5arguments?); // procedure call145
circ.setRadiusprocedureName?(30arguments?); // procedure call146
circ.setFillColourprocedureName?(greenarguments?); // procedure call147
vg.appendprocedureName?(circarguments?); // procedure call148
+while (truecondition?) {
149
displayVectorGraphicsprocedureName?(vgarguments?); // procedure call150
sleepprocedureName?(1arguments?); // procedure call151
circ.setFillColourprocedureName?(redarguments?); // procedure call152
displayVectorGraphicsprocedureName?(vgarguments?); // procedure call153
sleepprocedureName?(1arguments?); // procedure call154
circ.setFillColourprocedureName?(greenarguments?); // procedure call155
} // end while
displayVectorGraphicsprocedureName?(vgarguments?); // procedure call156
} // end main
RawVGRawVGRawVGRawVGRawVG
Strings containing raw SVG tags may be assembled and plotted directly using class RawVGRawVGRawVGRawVGRawVG.
By this means features such as simple SVG animation can be defined.
- The raw SVG content should be enclosed in double quotes within which the SVG attribute values must be enclosed in single quotes.
- To include interpolated values, you precede the string with a $.
- The raw SVG may define multiple shapes.
- Multiple instances of
RawVGRawVGRawVGRawVGRawVG may be added to the collection to be displayed, along with instances of other SVG types;
hence the need for list-defining square brackets in the parameter of method displayVectorGraphics.
- Method withContent is used to specify the property of class
RawVGRawVGRawVGRawVGRawVG that must contain the SVG string.
- The example is of a simple animation in which the repetition defined in the SVG continues after the program has stopped,
so you would then use the Clear button to blank the display.
Example using RawVGRawVGRawVGRawVGRawVG
● To display a repeating movement of a circle:
+main
157
variable movingCirclename? set to "<circle cx='50' cy='50' r='50' style='fill:red;'>\n<animate attributeName='cx' begin='0s' dur='2s' from='50' to='90%' repeatCount='indefinite' /></circle>"value or expression?158
variable rawname? set to (new RawVG()).withContent(movingCircle)value or expression?159
call displayVectorGraphicsprocedureName?([raw]arguments?)160
end main
+def main() -> None:
161
movingCirclename? = "<circle cx='50' cy='50' r='50' style='fill:red;'>\n<animate attributeName='cx' begin='0s' dur='2s' from='50' to='90%' repeatCount='indefinite' /></circle>"value or expression? # variable definition162
rawname? = (RawVG()).withContent(movingCircle)value or expression? # variable definition163
displayVectorGraphicsprocedureName?([raw]arguments?) # procedure call164
# end main
+static void main() {
165
var movingCirclename? = "<circle cx='50' cy='50' r='50' style='fill:red;'>\n<animate attributeName='cx' begin='0s' dur='2s' from='50' to='90%' repeatCount='indefinite' /></circle>"value or expression?;166
var rawname? = (new RawVG()).withContent(movingCircle)value or expression?;167
displayVectorGraphicsprocedureName?(new [] {raw}arguments?); // procedure call168
} // end main
+Sub main()
169
Dim movingCirclename? = "<circle cx='50' cy='50' r='50' style='fill:red;'>\n<animate attributeName='cx' begin='0s' dur='2s' from='50' to='90%' repeatCount='indefinite' /></circle>"value or expression? ' variable definition170
Dim rawname? = (New RawVG()).withContent(movingCircle)value or expression? ' variable definition171
displayVectorGraphicsprocedureName?({raw}arguments?) ' procedure call172
End Sub
+static void main() {
173
var movingCirclename? = "<circle cx='50' cy='50' r='50' style='fill:red;'>\n<animate attributeName='cx' begin='0s' dur='2s' from='50' to='90%' repeatCount='indefinite' /></circle>"value or expression?;174
var rawname? = (new RawVG()).withContent(movingCircle)value or expression?;175
displayVectorGraphicsprocedureName?(list(raw)arguments?); // procedure call176
} // end main
Combining graphic outputs
Program outputs, whether text or graphical, can be combined in the display. In particular, Block graphics and text or Html printing can share the display
along with either Vector graphics or Turtle graphics (but not both).
If you want to share the display in this way, remember that both text and Html print outputs appear sequentially down the display (which can be scrolled), whereas the graphic outputs are positioned in the display using their own absolute coordinate systems.
The order in which the outputs are displayed (and therefore overwrite) is:
- Block graphics
- Vector or Turtle graphics
- Printed text or Html
So some care is needed to manage the layout in the display.
Note that, while vector graphics are being drawn, printed text that exceeds the height of the display does not scroll until the graphic completes.
Other types
Random
Generating random numbers within a function
It is not possible to use the system methods random or randint within a function because they create unseen side effects. You may use those system methods outside the function and pass the resulting random number (as an IntintintIntegerint or a FloatfloatdoubleDoubledouble) as an argument into a function.
It is, however, possible to create and use random numbers within a function, but it requires a different approach and is a little more complex. You use the special type RandomRandomRandomRandomRandom. (Note the upper case R required for a type name).
You start by getting a seed random number in your main routine or in a procedure using method initialiseFromClock:
variable rndname? set to new Random()value or expression?41rndname? = Random()value or expression? # variable definition42var rndname? = new Random()value or expression?;43Dim rndname? = New Random()value or expression? ' variable definition44var rndname? = new Random()value or expression?;45
call rnd.initialiseFromClockprocedureName?(arguments?)46rnd.initialiseFromClockprocedureName?(arguments?) # procedure call47rnd.initialiseFromClockprocedureName?(arguments?); // procedure call48rnd.initialiseFromClockprocedureName?(arguments?) ' procedure call49rnd.initialiseFromClockprocedureName?(arguments?); // procedure call50
Then, in a function, apply dot method asFloat or asInt as appropriate to the RandomRandomRandomRandomRandom passed in,
and dot method nextGen to obtain a new instance of RandomRandomRandomRandomRandom for generating the next random number.
Avoid applying nextGen more than once on the same RandomRandomRandomRandomRandom instance, because it will return the same values.
If the initialiseFromClock call is absent, the program will still generate a sequence of random values, but the sequence will be exactly the same each time you run the program. Initialising from the clock ensures that you get a different sequence each run. Using RandomRandomRandomRandomRandom without so initialising, however, can be extremely useful for testing purposes since the results are repeatable.
Function method for random seed
procedure method |
argument type |
action |
| initialiseFromClock |
(none) |
uses the system clock to provide a seed from which to generate fresh random values |
Function dot methods on a RandomRandomRandomRandomRandom
function dot method |
argument types |
return type |
returns |
| asFloat |
(none) |
FloatfloatdoubleDoubledouble |
random FloatfloatdoubleDoubledouble value in the range (0.0, 1.0) |
| asInt |
IntintintIntegerint, IntintintIntegerint |
IntintintIntegerint |
random IntintintIntegerint value in the range of the arguments |
| nextGen |
(none) |
RandomRandomRandomRandomRandom |
a new instance of RandomRandomRandomRandomRandom for subsequent use |
Example using RandomRandomRandomRandomRandom
● To roll a dice 20 times in a function that returns a 2-tuple of random value and a new instance of RandomRandomRandomRandomRandom:
+main
1
variable rndname? set to new Random()value or expression?2
call rnd.initialiseFromClockprocedureName?(arguments?)3
+for iitem? in range(1, 20)source?
4
print(randomThrow(rnd).item_0value or expression?)5
assign rndvariableName? to randomThrow(rnd).item_1value or expression?6
end for
end main
+function randomThrowname?(rnd as Randomparameter definitions?) returns (Int, Random)Type?
7
return (rnd.asInt(1, 6), rnd.nextGen())value or expression?8
end function
+def main() -> None:
1
rndname? = Random()value or expression? # variable definition2
rnd.initialiseFromClockprocedureName?(arguments?) # procedure call3
+for iitem? in range(1, 20)source?:
4
print(randomThrow(rnd).item_0value or expression?)5
rndvariableName? = randomThrow(rnd).item_1value or expression? # assignment6
# end for
# end main
+def randomThrowname?(rnd: Randomparameter definitions?) -> tuple[int, Random]Type?:
# function7
return (rnd.asInt(1, 6), rnd.nextGen())value or expression?8
# end function
main()
+static void main() {
1
var rndname? = new Random()value or expression?;2
rnd.initialiseFromClockprocedureName?(arguments?); // procedure call3
+foreach (var iitem? in range(1, 20)source?) {
4
Console.WriteLine(randomThrow(rnd).item_0value or expression?); // print statement5
rndvariableName? = randomThrow(rnd).item_1value or expression?; // assignment6
} // end foreach
} // end main
+static (int, Random)Type? randomThrowname?(Random rndparameter definitions?) {
// function7
return (rnd.asInt(1, 6), rnd.nextGen())value or expression?;8
} // end function
+Sub main()
1
Dim rndname? = New Random()value or expression? ' variable definition2
rnd.initialiseFromClockprocedureName?(arguments?) ' procedure call3
+For Each iitem? In range(1, 20)source?
4
Console.WriteLine(randomThrow(rnd).item_0value or expression?) ' print statement5
rndvariableName? = randomThrow(rnd).item_1value or expression? ' assignment6
Next i
End Sub
+Function randomThrowname?(rnd As Randomparameter definitions?) As (Integer, Random)Type?
7
Return (rnd.asInt(1, 6), rnd.nextGen())value or expression?8
End Function
public class Global {
+static void main() {
1
var rndname? = new Random()value or expression?;2
rnd.initialiseFromClockprocedureName?(arguments?); // procedure call3
+foreach (var iitem? in range(1, 20)source?) {
4
System.out.println(randomThrow(rnd).item_0value or expression?); // print statement5
rndvariableName? = randomThrow(rnd).item_1value or expression?; // assignment6
} // end foreach
} // end main
+static (int, Random)Type? randomThrowname?(Random rndparameter definitions?) {
// function7
return (rnd.asInt(1, 6), rnd.nextGen())value or expression?;8
} // end function
}
// end Global
This section covers a variety of input and output facilities:
soliciting and retrieving keyboard input requires using these system methods:
system method |
argument types |
return types |
action |
| getKey |
(none) |
StringstrstringStringString |
returns the last character last pressed on the keyboard during program execution |
| getKeyWithModifier |
(none) |
2-tuple: (StringstrstringStringString, StringstrstringStringString) |
returns the last key combination pressed on the keyboard:
the key pressed and the modifier key's name (if also pressed) |
| getNumericKey |
(none) |
StringstrstringStringString |
returns either the numeric key last pressed or, if the last pressed key was not numeric, then "-1" |
| input |
StringstrstringStringString |
StringstrstringStringString |
prints the string as a prompt, and returns the typed input when Enter is pressed, similar to the input statement. |
| inputStringWithLimits |
StringstrstringStringString, IntintintIntegerint, IntintintIntegerint |
StringstrstringStringString |
prints the string as a prompt and returns the typed input when Enter is pressed
provided the length of the response is within the minimum and maximum limits specified.
If it is not, the prompt is repeated with the relevant limit displayed |
| inputStringFromOptions |
StringstrstringStringString, List<of String>list[str]List<string>List(Of String)List<String> |
StringstrstringStringString |
prints the string as a prompt and returns the typed input when Enter is pressed
provided it is one of the options in the ListlistListListList.
If it is not, the prompt is repeated with the options displayed |
| inputInt |
StringstrstringStringString |
IntintintIntegerint |
prints the string as a prompt and returns the value of the typed input when Enter is pressed
provided that it is an integer. If it is not, the prompt is repeated with an error message |
| inputIntBetween |
StringstrstringStringString, IntintintIntegerint, IntintintIntegerint |
IntintintIntegerint |
prints the string as a prompt and returns the value of the typed input when Enter is pressed
provided that it is an integer with a value in the (inclusive) range. The first range value must be less than or equal to the second |
| inputFloat |
StringstrstringStringString |
FloatfloatdoubleDoubledouble |
prints the string as a prompt and returns the value of the typed input when Enter is pressed
provided that it is a number. If it is not, the prompt is repeated with an error message |
| inputFloatBetween |
StringstrstringStringString, IntintintIntegerint, IntintintIntegerint |
FloatfloatdoubleDoubledouble |
prints the string as a prompt and returns the value of the typed input when Enter is pressed
provided that it is a number with a value in the (inclusive) range. The first range value must be less than or equal to the second |
| waitForKey |
(none) |
StringstrstringStringString |
pauses execution of the program until a key is pressed on the keyboard,
and returns either a character or the name of a non-character key |
Reading keys 'on the fly'
In some applications – especially in games, for example – you want the program to react to a key pressed by the user, but without holding up the program to wait for value to be input.
Whether your application makes use of graphics, or uses the display just for text, reading keystrokes 'on the fly' is done via one of the three methods shown here:
+main
9
variable key1name? set to getKey()value or expression?10
variable key2name? set to getNumericKey()value or expression?11
variable kmname? set to getKeyWithModifier()value or expression?12
variable keyCapname? set to km.item_0value or expression?13
variable keyModname? set to km.item_1value or expression?14
end main
+def main() -> None:
15
key1name? = getKey()value or expression? # variable definition16
key2name? = getNumericKey()value or expression? # variable definition17
kmname? = getKeyWithModifier()value or expression? # variable definition18
keyCapname? = km.item_0value or expression? # variable definition19
keyModname? = km.item_1value or expression? # variable definition20
# end main
+static void main() {
21
var key1name? = getKey()value or expression?;22
var key2name? = getNumericKey()value or expression?;23
var kmname? = getKeyWithModifier()value or expression?;24
var keyCapname? = km.item_0value or expression?;25
var keyModname? = km.item_1value or expression?;26
} // end main
+Sub main()
27
Dim key1name? = getKey()value or expression? ' variable definition28
Dim key2name? = getNumericKey()value or expression? ' variable definition29
Dim kmname? = getKeyWithModifier()value or expression? ' variable definition30
Dim keyCapname? = km.item_0value or expression? ' variable definition31
Dim keyModname? = km.item_1value or expression? ' variable definition32
End Sub
+static void main() {
33
var key1name? = getKey()value or expression?;34
var key2name? = getNumericKey()value or expression?;35
var kmname? = getKeyWithModifier()value or expression?;36
var keyCapname? = km.item_0value or expression?;37
var keyModname? = km.item_1value or expression?;38
} // end main
- When any of these functions (except waitForKey) is called, the system does not wait for a response, but immediately returns a
StringstrstringStringString or Tuple.
- getKey returns a string containing the keyboard character last pressed, possibly shifted, e.g. "z" or "@".
- getNumericKey returns a string containing either a digit ("0".."9") or, if the last key pressed was not numeric, then "-1".
A digit will be returned if the key pressed was either from the main keyboard, or from the numeric keypad when NumLock is on.
- getKeyWithModifier returns a 2-tuple of two strings: the key last pressed and the name of one modifier key
"Shift""Shift""Shift""Shift""Shift",
"Ctrl""Ctrl""Ctrl""Ctrl""Ctrl" or "Alt""Alt""Alt""Alt""Alt" if simultaneously pressed.
If no modifier had been pressed, the Tuple's second item will be the empty string. Note that a few such modified keys will be acted on by the browser and may not then be passed to your program.
- Non-printable keys will also be returned as strings, e.g.
"Home""Home""Home""Home""Home", "End""End""End""End""End", "Delete""Delete""Delete""Delete""Delete", "Tab""Tab""Tab""Tab""Tab",
"Backspace""Backspace""Backspace""Backspace""Backspace", "Enter""Enter""Enter""Enter""Enter", "Escape""Escape""Escape""Escape""Escape",
"ArrowUp""ArrowUp""ArrowUp""ArrowUp""ArrowUp" etc., function key "Fn""Fn""Fn""Fn""Fn", "AltGraph""AltGraph""AltGraph""AltGraph""AltGraph", "Meta""Meta""Meta""Meta""Meta", "ContextMenu""ContextMenu""ContextMenu""ContextMenu""ContextMenu", as well as most others.
- Pressing just control keys Shift, Ctrl (⌘ Command under macOS) or Alt keys will not be detected by getKey.
- If no key has been pressed (since the last time the method was called), it will return the empty string.
- All these methods are system methods because they have a dependency on the system and so may be used only within a procedure or in main routine.
- Use the procedure method clearKeyBuffer if you want to enforce that the user cannot get too far ahead of the program by hitting keys in rapid succession.
- Method waitForKey waits for a key to be pressed, and returns it.
- Procedure methodpressAnyKeyToContinue gives an optional prompt and is used when you don't need to know which key was pressed. Its argument is a Boolean value:
if trueTruetrueTruetrue, the prompt "Press any key to continue" appears,
if falseFalsefalseFalsefalse, no prompt appears.
+main
39
call pressAnyKeyToContinueprocedureName?(arguments?)40
print("OK, press A or B"value or expression?)41
variable keyname? set to waitForKey()value or expression?42
print($"That was {key}"value or expression?)43
end main
+def main() -> None:
44
pressAnyKeyToContinueprocedureName?(arguments?) # procedure call45
print("OK, press A or B"value or expression?)46
keyname? = waitForKey()value or expression? # variable definition47
print(f"That was {key}"value or expression?)48
# end main
+static void main() {
49
pressAnyKeyToContinueprocedureName?(arguments?); // procedure call50
Console.WriteLine("OK, press A or B"value or expression?); // print statement51
var keyname? = waitForKey()value or expression?;52
Console.WriteLine($"That was {key}"value or expression?); // print statement53
} // end main
+Sub main()
54
pressAnyKeyToContinueprocedureName?(arguments?) ' procedure call55
Console.WriteLine("OK, press A or B"value or expression?) ' print statement56
Dim keyname? = waitForKey()value or expression? ' variable definition57
Console.WriteLine($"That was {key}"value or expression?) ' print statement58
End Sub
+static void main() {
59
pressAnyKeyToContinueprocedureName?(arguments?); // procedure call60
System.out.println("OK, press A or B"value or expression?); // print statement61
var keyname? = waitForKey()value or expression?;62
System.out.println(String.format("That was %", key)value or expression?); // print statement63
} // end main
Reading or writing a text file requires that you open (for reading) or create (for writing) a file using these system methods:
system method |
argument types |
return class |
action |
| createFileForWriting |
StringstrstringStringString |
TextFileWriterTextFileWriterTextFileWriterTextFileWriterTextFileWriter |
sets up a buffer for the data to be output, and specifies a filename (or the empty string)
with or without the default filetype of .txt, and returns a file handle
see Writing text files |
| openFileForReading |
(none) |
TextFileReaderTextFileReaderTextFileReaderTextFileReaderTextFileReader |
opens a file system dialog to choose the filename of filetype .txt to be read,
and returns a file handle
see Reading text files |
Writing text files
The TextFileWriterTextFileWriterTextFileWriterTextFileWriterTextFileWriter class is used to write textual data to a file.
An instance is created by the system method createFileForWriting.
The available procedure methods are:
procedure method |
argument type |
action |
| writeLine |
StringstrstringStringString |
writes the string to the buffer |
| writeWholeFile |
StringstrstringStringString |
writes the string to the buffer and then outputs the buffer to the file system |
| saveAndClose |
none |
writes the buffer to the file system |
These methods may be used to write a whole file in one go:
+main
64
variable filename? set to createFileForWriting("myFile.txt")value or expression?65
call file.writeWholeFileprocedureName?("Text line 1\nText line 2"arguments?)66
end main
+def main() -> None:
67
filename? = createFileForWriting("myFile.txt")value or expression? # variable definition68
file.writeWholeFileprocedureName?("Text line 1\nText line 2"arguments?) # procedure call69
# end main
+static void main() {
70
var filename? = createFileForWriting("myFile.txt")value or expression?;71
file.writeWholeFileprocedureName?("Text line 1\nText line 2"arguments?); // procedure call72
} // end main
+Sub main()
73
Dim filename? = createFileForWriting("myFile.txt")value or expression? ' variable definition74
file.writeWholeFileprocedureName?("Text line 1\nText line 2"arguments?) ' procedure call75
End Sub
+static void main() {
76
var filename? = createFileForWriting("myFile.txt")value or expression?;77
file.writeWholeFileprocedureName?("Text line 1\nText line 2"arguments?); // procedure call78
} // end main
Notes
writeLinewriteLinewriteLinewriteLinewriteLine adds the string it is passed onto the end of any data previously written, with a newline character (\n) automatically appended.
- When execution reaches
saveAndClosesaveAndClosesaveAndClosesaveAndClosesaveAndClose you will be presented with a dialog to confirm (or edit) the given filename and location where it is to be saved. It is not therefore strictly necessary to specify a filename when creating the file, since it can be specified by the user in the dialog so, in that case, you might put the empty string """""""""" into the parameter of createFileForWritingcreateFileForWritingcreateFileForWritingcreateFileForWritingcreateFileForWriting.
writeWholeFilewriteWholeFilewriteWholeFilewriteWholeFilewriteWholeFile puts the string it is given into the file and then automatically saves the file, so the user will be presented with the same dialog as if saveAndClosesaveAndClosesaveAndClosesaveAndClosesaveAndClose had been called.
- Calling any method on a file that has already been closed (by calling either
saveAndClosesaveAndClosesaveAndClosesaveAndClosesaveAndClose or by writeWholeFilewriteWholeFilewriteWholeFilewriteWholeFilewriteWholeFile) will result in a runtime error.
- If the user were to click Cancel in the save dialogue, then the program will exit with an error.
To guard against this possibility (it might mean the loss of important data), you should perform the save and close within a try statement like this (where
CustomErrorCustomErrorCustomErrorCustomErrorCustomError is a class provided by Elan for this purpose):
+main
79
variable filename? set to createFileForWriting("squares.txt")value or expression?80
+for iitem? in range(1, (101))source?
81
call file.writeLineprocedureName?($"{i*i}"arguments?)82
end for
+try
83
call file.saveAndCloseprocedureName?(arguments?)84
catch evariableName? as CustomErrortype e.g. ElanRuntimeError or CustomError?85
print("Save cancelled"value or expression?)86
end try
end main
+def main() -> None:
87
filename? = createFileForWriting("squares.txt")value or expression? # variable definition88
+for iitem? in range(1, (101))source?:
89
file.writeLineprocedureName?(f"{i*i}"arguments?) # procedure call90
# end for
+try:
91
file.saveAndCloseprocedureName?(arguments?) # procedure call92
except CustomErrortype e.g. ElanRuntimeError or CustomError? as evariableName?: # catch93
print("Save cancelled"value or expression?)94
# end try
# end main
+static void main() {
95
var filename? = createFileForWriting("squares.txt")value or expression?;96
+foreach (var iitem? in range(1, (101))source?) {
97
file.writeLineprocedureName?($"{i*i}"arguments?); // procedure call98
} // end foreach
+try {
99
file.saveAndCloseprocedureName?(arguments?); // procedure call100
} catch (CustomErrortype e.g. ElanRuntimeError or CustomError? evariableName?) {101
Console.WriteLine("Save cancelled"value or expression?); // print statement102
} // end try
} // end main
+Sub main()
103
Dim filename? = createFileForWriting("squares.txt")value or expression? ' variable definition104
+For Each iitem? In range(1, (101))source?
105
file.writeLineprocedureName?($"{i*i}"arguments?) ' procedure call106
Next i
+Try
107
file.saveAndCloseprocedureName?(arguments?) ' procedure call108
Catch evariableName? As CustomErrortype e.g. ElanRuntimeError or CustomError?109
Console.WriteLine("Save cancelled"value or expression?) ' print statement110
End Try
End Sub
+static void main() {
111
var filename? = createFileForWriting("squares.txt")value or expression?;112
+foreach (var iitem? in range(1, (101))source?) {
113
file.writeLineprocedureName?(String.format("%", i*i)arguments?); // procedure call114
} // end foreach
+try {
115
file.saveAndCloseprocedureName?(arguments?); // procedure call116
} catch (CustomErrortype e.g. ElanRuntimeError or CustomError? evariableName?) {117
System.out.println("Save cancelled"value or expression?); // print statement118
} // end try
} // end main
or you could make the code offer the user options: to save again, or to continue without saving.
Reading text files
The TextFileReaderTextFileReaderTextFileReaderTextFileReaderTextFileReader class is used to read text data from a file with type extension .txt.
An instance is created by the system method openFileForReading.
The available procedure methods are:
procedure method |
argument type |
action |
| readLine |
(none) |
reads the next substring from the file that is terminated with a newline |
| readWholeFile |
(none) |
reads the whole file and closes the file |
| endOfFile |
(none) |
returns trueTruetrueTruetrue after the last line has been read
– otherwise falseFalsefalseFalsefalse |
| close |
(none) |
closes the file |
These methods may be used to read a whole file in one go:
+main
119
variable filename? set to openFileForReading()value or expression?120
variable textname? set to file.readWholeFile()value or expression?121
print(textvalue or expression?)122
end main
+def main() -> None:
123
filename? = openFileForReading()value or expression? # variable definition124
textname? = file.readWholeFile()value or expression? # variable definition125
print(textvalue or expression?)126
# end main
+static void main() {
127
var filename? = openFileForReading()value or expression?;128
var textname? = file.readWholeFile()value or expression?;129
Console.WriteLine(textvalue or expression?); // print statement130
} // end main
+Sub main()
131
Dim filename? = openFileForReading()value or expression? ' variable definition132
Dim textname? = file.readWholeFile()value or expression? ' variable definition133
Console.WriteLine(textvalue or expression?) ' print statement134
End Sub
+static void main() {
135
var filename? = openFileForReading()value or expression?;136
var textname? = file.readWholeFile()value or expression?;137
System.out.println(textvalue or expression?); // print statement138
} // end main
Notes
openFileForReadingopenFileForReadingopenFileForReadingopenFileForReadingopenFileForReading will present the user with a dialog to select the file.
readWholeFilereadWholeFilereadWholeFilereadWholeFilereadWholeFile returns a StringstrstringStringString containing every character in the file, without any trimming. It automatically closes the file after the read.
readLinereadLinereadLinereadLinereadLine reads as far as the next newline character (\n) and then automatically trims the line to remove any spaces and/or carriage-returns (which some file systems insert after the newline automatically) from the resulting line returned as a StringstrstringStringString. If this behaviour is not desired, you can use readWholeFilereadWholeFilereadWholeFilereadWholeFilereadWholeFile, which does no trimming, and then parse the resulting StringstrstringStringString into separate lines.
- Calling
file.closefile.closefile.closefile.closefile.close after reading line by line is strongly recommended to avoid any risk of leaving the file locked. It is not necessary to call it after using readWholeFilereadWholeFilereadWholeFilereadWholeFilereadWholeFile because that method automatically closes the file.
- Calling any method on a file that is already closed will result in a runtime error.
Rendering Html in the display
If you embed Html code in a string and then attempt to print it, you will see the string displayed literally: the Html tags
will not be recognised. This is for security reasons. However, it is possible to display formatted Html in the display.
The following code:
call displayHtmlprocedureName?("<h1 style='color: blue;'>A heading</h1><p>some text</p>"arguments?)139
displayHtmlprocedureName?("<h1 style='color: blue;'>A heading</h1><p>some text</p>"arguments?) # procedure call140
displayHtmlprocedureName?("<h1 style='color: blue;'>A heading</h1><p>some text</p>"arguments?); // procedure call141
displayHtmlprocedureName?("<h1 style='color: blue;'>A heading</h1><p>some text</p>"arguments?) ' procedure call142
displayHtmlprocedureName?("<h1 style='color: blue;'>A heading</h1><p>some text</p>"arguments?); // procedure call143
will produce:

This Html forms another 'layer' in the IDE's display pane. Any plain text that you print
(using call procedure print() or any of the print procedures)
will be overlaid on top of this.
You can clear just the Html layer in the display using the procedure clearHtml .
For specifying style or other attributes within Html tags, the attribute values should be enclosed in single quotation marks ' as shown above.
Html will recognise single or double quotation marks, but entering double quotation marks would terminate the Elan string.
Alternatively, you could use the constant quotesquotesquotesquotesquotes within curly braces as an interpolated field .
Using an embedded CSS stylesheet
You can also specify a <style> tag at the start of your Html string, to apply to the whole Html being displayed. In this case you would put
the style definition into a named value as a literal but enclosed in single quotes, for example:
+main
144
variable stylename? set to "<style> h1 { color: Red; font-size: 24pt; } p { font-family: Serif; } </style>"value or expression?145
call displayHtmlprocedureName?($"{style}<h1>New heading</h1><p>some new text</p>"arguments?)146
end main
+def main() -> None:
147
stylename? = "<style> h1 { color: Red; font-size: 24pt; } p { font-family: Serif; } </style>"value or expression? # variable definition148
displayHtmlprocedureName?(f"{style}<h1>New heading</h1><p>some new text</p>"arguments?) # procedure call149
# end main
+static void main() {
150
var stylename? = "<style> h1 { color: Red; font-size: 24pt; } p { font-family: Serif; } </style>"value or expression?;151
displayHtmlprocedureName?($"{style}<h1>New heading</h1><p>some new text</p>"arguments?); // procedure call152
} // end main
+Sub main()
153
Dim stylename? = "<style> h1 { color: Red; font-size: 24pt; } p { font-family: Serif; } </style>"value or expression? ' variable definition154
displayHtmlprocedureName?($"{style}<h1>New heading</h1><p>some new text</p>"arguments?) ' procedure call155
End Sub
+static void main() {
156
var stylename? = "<style> h1 { color: Red; font-size: 24pt; } p { font-family: Serif; } </style>"value or expression?;157
displayHtmlprocedureName?(String.format("%<h1>New heading</h1><p>some new text</p>", style)arguments?); // procedure call158
} // end main
will produce:

Displaying images from URLs
An image that can be retrieved with an http or https URL may be sent to the display, though note that other URI schemes,
such as in file://host/path to access an image from your local file system, are not supported. Here are two techniques:
Sound
The tone procedure allows the generation of a simple tone. It requires three arguments to be provided:
- the duration of the generated tone specified in milliseconds (
IntintintIntegerint)
- the frequency of the generated tone in Hertz (
IntintintIntegerint)
- the volume of the tone (
FloatfloatdoubleDoubledouble)
Note that the volume parameter is only relative in that the actual volume will be modified by the various sound settings on the output device, and may even be muted.
Example using tone
● An example that plays a C major scale first ascending then descending:
+main
209
variable scalename? set to [262, 294, 330, 349, 392, 440, 494, 523]value or expression?210
variable scaleLname? set to scale.length()value or expression?211
variable quavername? set to 250value or expression?212
variable volumename? set to 1.5value or expression?213
+for iitem? in range(0, scaleL)source?
214
call toneprocedureName?(quaver, scale[i], volumearguments?)215
end for
call sleepprocedureName?(1arguments?)216
+for iitem? in range(0, scaleL)source?
217
call toneprocedureName?(quaver, scale[scaleL - 1 - i], volumearguments?)218
end for
end main
+def main() -> None:
219
scalename? = [262, 294, 330, 349, 392, 440, 494, 523]value or expression? # variable definition220
scaleLname? = scale.length()value or expression? # variable definition221
quavername? = 250value or expression? # variable definition222
volumename? = 1.5value or expression? # variable definition223
+for iitem? in range(0, scaleL)source?:
224
toneprocedureName?(quaver, scale[i], volumearguments?) # procedure call225
# end for
sleepprocedureName?(1arguments?) # procedure call226
+for iitem? in range(0, scaleL)source?:
227
toneprocedureName?(quaver, scale[scaleL - 1 - i], volumearguments?) # procedure call228
# end for
# end main
+static void main() {
229
var scalename? = new [] {262, 294, 330, 349, 392, 440, 494, 523}value or expression?;230
var scaleLname? = scale.length()value or expression?;231
var quavername? = 250value or expression?;232
var volumename? = 1.5value or expression?;233
+foreach (var iitem? in range(0, scaleL)source?) {
234
toneprocedureName?(quaver, scale[i], volumearguments?); // procedure call235
} // end foreach
sleepprocedureName?(1arguments?); // procedure call236
+foreach (var iitem? in range(0, scaleL)source?) {
237
toneprocedureName?(quaver, scale[scaleL - 1 - i], volumearguments?); // procedure call238
} // end foreach
} // end main
+Sub main()
239
Dim scalename? = {262, 294, 330, 349, 392, 440, 494, 523}value or expression? ' variable definition240
Dim scaleLname? = scale.length()value or expression? ' variable definition241
Dim quavername? = 250value or expression? ' variable definition242
Dim volumename? = 1.5value or expression? ' variable definition243
+For Each iitem? In range(0, scaleL)source?
244
toneprocedureName?(quaver, scale(i), volumearguments?) ' procedure call245
Next i
sleepprocedureName?(1arguments?) ' procedure call246
+For Each iitem? In range(0, scaleL)source?
247
toneprocedureName?(quaver, scale(scaleL - 1 - i), volumearguments?) ' procedure call248
Next i
End Sub
+static void main() {
249
var scalename? = list(262, 294, 330, 349, 392, 440, 494, 523)value or expression?;250
var scaleLname? = scale.length()value or expression?;251
var quavername? = 250value or expression?;252
var volumename? = 1.5value or expression?;253
+foreach (var iitem? in range(0, scaleL)source?) {
254
toneprocedureName?(quaver, scale[i], volumearguments?); // procedure call255
} // end foreach
sleepprocedureName?(1arguments?); // procedure call256
+foreach (var iitem? in range(0, scaleL)source?) {
257
toneprocedureName?(quaver, scale[scaleL - 1 - i], volumearguments?); // procedure call258
} // end foreach
} // end main
Common methods
Common dot methods
Click on a type to go to the type's function dot methods, or on to go to the specific method on that type.
Notes
- The method toString is so widely applicable because it enables you to print
all variables and data structures to the IDE's display pane for debugging purposes.
- methods ceiling, floor, isInfinite, isNaN and round are designed for use on
FloatfloatdoubleDoubledouble values, but they can accept IntintintIntegerint values without raising an error.
- The length of a
DictionaryDictionaryDictionaryDictionaryDictionary can be found by applying method length to the ListlistListListList returned by method keys on the dictionary:
print(di.keys().length())print(di.keys().length())print(di.keys().length())print(di.keys().length())print(di.keys().length()) | ⟶ | 15 |
- Checking whether an item is contained in a
DictionaryDictionaryDictionaryDictionaryDictionary can be
done by applying method contains to the ListlistListListList returned by methods keys and values on the dictionary:
print(di.keys().contains("widget"))print(di.keys().contains("widget"))print(di.keys().contains("widget"))print(di.keys().contains("widget"))print(di.keys().contains("widget")) | ⟶ | true or false |
print(di.values().contains(42))print(di.values().contains(42))print(di.values().contains(42))print(di.values().contains(42))print(di.values().contains(42)) | ⟶ | true or false |
- withPut supersedes the deprecated withSet
Library procedures
All procedures are accessed via a callcallcallcallcall instruction.
Standalone procedures
| procedure | input argument types | output argument types | action |
|---|
| clearPrintedText |
(none) |
(none) |
clears the IDE's display pane |
| clearBlocks |
(none) |
(none) |
clears the block graphics layer of the IDE's display pane |
| clearVectorGraphics |
(none) |
(none) |
clears the vector graphics layer of the IDE's display pane |
| clearHtml |
(none) |
(none) |
clears the Html layer of the IDE's display pane |
| clearAllDisplays |
(none) |
(none) |
clears display pane as well as the blocks, vector graphics and Html layers |
| clearKeyBuffer |
(none) |
(none) |
clears the IDE's keyboard input |
| pressAnyKeyToContinue |
BooleanboolboolBooleanboolean |
(none) |
pauses execution of the program until a keyboard key is pressed
if the argument is trueTruetrueTruetrue 'Press any key to continue' is first displayed,
if falseFalsefalseFalsefalse nothing is displayed |
| printNoLine |
StringstrstringStringString |
(none) |
prints the string to the display without appending a newline so
a following call will output on the same line.
You can put your own \n newlines in the argument string |
| printTab |
IntintintIntegerint, StringstrstringStringString |
(none) |
prints the string to the display starting at the tab position given (from 0) without appending a newline |
| sleep |
IntintintIntegerint |
(none) |
pauses the execution of the program for the specified number of seconds, e.g. for a game sleep(1.5)sleep(1.5)sleep(1.5)sleep(1.5)sleep(1.5) delays execution for 1.5 seconds |
| sleep_ms |
IntintintIntegerint |
(none) |
pauses the execution of the program for the specified number of milliseconds, e.g. sleep(100)sleep(100)sleep(100)sleep(100)sleep(100) delays execution for one tenth of a second |
Examples using print and printTab
● Procedure print sends text strings to the display pane:
+main
259
print("Hello"value or expression?)260
variable aname? set to 3value or expression?261
variable bname? set to 4value or expression?262
print(a*bvalue or expression?)263
print($"{a} times {b}) equals {a*b}"value or expression?)264
variable tname? set to (true, 42)value or expression?265
print(t.item_0value or expression?)266
print(t.item_1value or expression?)267
end main
+def main() -> None:
268
print("Hello"value or expression?)269
aname? = 3value or expression? # variable definition270
bname? = 4value or expression? # variable definition271
print(a*bvalue or expression?)272
print(f"{a} times {b}) equals {a*b}"value or expression?)273
tname? = (True, 42)value or expression? # variable definition274
print(t.item_0value or expression?)275
print(t.item_1value or expression?)276
# end main
+static void main() {
277
Console.WriteLine("Hello"value or expression?); // print statement278
var aname? = 3value or expression?;279
var bname? = 4value or expression?;280
Console.WriteLine(a*bvalue or expression?); // print statement281
Console.WriteLine($"{a} times {b}) equals {a*b}"value or expression?); // print statement282
var tname? = (true, 42)value or expression?;283
Console.WriteLine(t.item_0value or expression?); // print statement284
Console.WriteLine(t.item_1value or expression?); // print statement285
} // end main
+Sub main()
286
Console.WriteLine("Hello"value or expression?) ' print statement287
Dim aname? = 3value or expression? ' variable definition288
Dim bname? = 4value or expression? ' variable definition289
Console.WriteLine(a*bvalue or expression?) ' print statement290
Console.WriteLine($"{a} times {b}) equals {a*b}"value or expression?) ' print statement291
Dim tname? = (True, 42)value or expression? ' variable definition292
Console.WriteLine(t.item_0value or expression?) ' print statement293
Console.WriteLine(t.item_1value or expression?) ' print statement294
End Sub
+static void main() {
295
System.out.println("Hello"value or expression?); // print statement296
var aname? = 3value or expression?;297
var bname? = 4value or expression?;298
System.out.println(a*bvalue or expression?); // print statement299
System.out.println(String.format("% times %) equals %", a, b, a*b)value or expression?); // print statement300
var tname? = (true, 42)value or expression?;301
System.out.println(t.item_0value or expression?); // print statement302
System.out.println(t.item_1value or expression?); // print statement303
} // end main
|
⟶
⟶ ⟶
⟶ ⟶ |
Hello
12 3 times 4 equals 12 [using interpolated strings ] [defining a 2-tuple ] true 42 |
● Procedure printTab helps in the layout of information printed to the display, e.g. when printing columns of data:
+main
304
call printTabprocedureName?(0, "Number"arguments?)305
call printTabprocedureName?(10, "Square"arguments?)306
call printTabprocedureName?(20, "Cube\n"arguments?)307
+for iitem? in range(1, 11)source?
308
call printTabprocedureName?(0, i.toString()arguments?)309
call printTabprocedureName?(10, $"{pow(i, 2)}"arguments?)310
call printTabprocedureName?(20, $"{pow(i, 3)}\n"arguments?)311
end for
end main
+def main() -> None:
312
printTabprocedureName?(0, "Number"arguments?) # procedure call313
printTabprocedureName?(10, "Square"arguments?) # procedure call314
printTabprocedureName?(20, "Cube\n"arguments?) # procedure call315
+for iitem? in range(1, 11)source?:
316
printTabprocedureName?(0, i.toString()arguments?) # procedure call317
printTabprocedureName?(10, f"{pow(i, 2)}"arguments?) # procedure call318
printTabprocedureName?(20, f"{pow(i, 3)}\n"arguments?) # procedure call319
# end for
# end main
+static void main() {
320
printTabprocedureName?(0, "Number"arguments?); // procedure call321
printTabprocedureName?(10, "Square"arguments?); // procedure call322
printTabprocedureName?(20, "Cube\n"arguments?); // procedure call323
+foreach (var iitem? in range(1, 11)source?) {
324
printTabprocedureName?(0, i.toString()arguments?); // procedure call325
printTabprocedureName?(10, $"{pow(i, 2)}"arguments?); // procedure call326
printTabprocedureName?(20, $"{pow(i, 3)}\n"arguments?); // procedure call327
} // end foreach
} // end main
+Sub main()
328
printTabprocedureName?(0, "Number"arguments?) ' procedure call329
printTabprocedureName?(10, "Square"arguments?) ' procedure call330
printTabprocedureName?(20, "Cube\n"arguments?) ' procedure call331
+For Each iitem? In range(1, 11)source?
332
printTabprocedureName?(0, i.toString()arguments?) ' procedure call333
printTabprocedureName?(10, $"{pow(i, 2)}"arguments?) ' procedure call334
printTabprocedureName?(20, $"{pow(i, 3)}\n"arguments?) ' procedure call335
Next i
End Sub
+static void main() {
336
printTabprocedureName?(0, "Number"arguments?); // procedure call337
printTabprocedureName?(10, "Square"arguments?); // procedure call338
printTabprocedureName?(20, "Cube\n"arguments?); // procedure call339
+foreach (var iitem? in range(1, 11)source?) {
340
printTabprocedureName?(0, i.toString()arguments?); // procedure call341
printTabprocedureName?(10, String.format("%", pow(i, 2))arguments?); // procedure call342
printTabprocedureName?(20, String.format("%\n", pow(i, 3))arguments?); // procedure call343
} // end foreach
} // end main
● For numeric output, it is preferable to right-align the columns, e.g. when listing powers of 9:
+main
1
variable tabname? set to 10value or expression?2
+for iitem? in range(1, tab)source?
3
variable jname? set to pow(9, i).floor()value or expression?4
call printTabprocedureName?(tab - strLen(j), $"{j}\n"arguments?)5
end for
end main
+function strLenname?(j as Intparameter definitions?) returns IntType?
6
return j.toString().length()value or expression?7
end function
+def main() -> None:
1
tabname? = 10value or expression? # variable definition2
+for iitem? in range(1, tab)source?:
3
jname? = pow(9, i).floor()value or expression? # variable definition4
printTabprocedureName?(tab - strLen(j), f"{j}\n"arguments?) # procedure call5
# end for
# end main
+def strLenname?(j: intparameter definitions?) -> intType?:
# function6
return j.toString().length()value or expression?7
# end function
main()
+static void main() {
1
var tabname? = 10value or expression?;2
+foreach (var iitem? in range(1, tab)source?) {
3
var jname? = pow(9, i).floor()value or expression?;4
printTabprocedureName?(tab - strLen(j), $"{j}\n"arguments?); // procedure call5
} // end foreach
} // end main
+static intType? strLenname?(int jparameter definitions?) {
// function6
return j.toString().length()value or expression?;7
} // end function
+Sub main()
1
Dim tabname? = 10value or expression? ' variable definition2
+For Each iitem? In range(1, tab)source?
3
Dim jname? = pow(9, i).floor()value or expression? ' variable definition4
printTabprocedureName?(tab - strLen(j), $"{j}\n"arguments?) ' procedure call5
Next i
End Sub
+Function strLenname?(j As Integerparameter definitions?) As IntegerType?
6
Return j.toString().length()value or expression?7
End Function
public class Global {
+static void main() {
1
var tabname? = 10value or expression?;2
+foreach (var iitem? in range(1, tab)source?) {
3
var jname? = pow(9, i).floor()value or expression?;4
printTabprocedureName?(tab - strLen(j), String.format("%\n", j)arguments?); // procedure call5
} // end foreach
} // end main
+static intType? strLenname?(int jparameter definitions?) {
// function6
return j.toString().length()value or expression?;7
} // end function
}
// end Global
Type instance procedures
Procedures applicable to standard Reference types are linked from:
User-defined classes may have procedures that can be applied to their class instances.
Library methods
These methods may be referenced from within a function.
Standalone functions
Standalone library functions always return a value and are therefore used in contexts that expect a value, such as in the right-hand side of a variable definition declaration or an assign variable, either on their own or within a more complex expression.
Standalone library functions require at least one argument to be passed (in round brackets), corresponding to the parameters defined for that function.
These methods are pure functions and so may be referenced in your functions as well as in procedures:
library method |
argument types |
return types |
returns |
| copy |
named value of any type |
same type as argument |
a copy of the named value |
| createBlockGraphics |
IntintintIntegerint |
List<of List<of Int>>list[list[int]]List<List<int>>List(Of List(Of Integer))List<List<int>> |
a 40×30 array with the specified value in every cell |
| createDictionary |
ListlistListListList of 2-tuples, each containg a key:value pair |
new codenew codenew codenew codepublic class Global {
new code
} // end Global |
a Dictionary containing the specified key:value pairs |
| createPopulatedList |
IntintintIntegerint, value of ListlistListListList item's type |
new codenew codenew codenew codepublic class Global {
new code
} // end Global |
a ListlistListListList containing the specified number of items each initialised to the value in the second argument |
| createPopulatedListofLists |
IntintintIntegerint, IntintintIntegerint, value of ListlistListListList item's type |
new codenew codenew codenew codepublic class Global {
new code
} // end Global |
a ListlistListListList of length the first argument containing that number of ListlistListListLists
each initialised to a ListlistListListList of length the second argument
with each item therein initialised to the value in the third argument |
| max |
List<of Int>list[int]List<int>List(Of Integer)List<int> or List<of Float>list[float]List<double>List(Of Double)List<double> |
IntintintIntegerint or FloatfloatdoubleDoubledouble |
the maximum value found in the ListlistListListList |
| min |
List<of Int>list[int]List<int>List(Of Integer)List<int> or List<of Float>list[float]List<double>List(Of Double)List<double> |
IntintintIntegerint or FloatfloatdoubleDoubledouble |
the minimum value found in the ListlistListListList |
| range |
IntintintIntegerint, IntintintIntegerint |
ListlistListListList |
a ListlistListListList containing the integers from the first argument to one less than the second argument.
If the second argument is not greater than the first, then the empty ListlistListListList is returned |
| rangeInSteps |
IntintintIntegerint, IntintintIntegerint, IntintintIntegerint |
ListlistListListList |
a ListlistListListList containing the integers from the first argument to one less than the second argument
in increments specified by the third argument.
If the third argument is negative, the second argument must be less than the first,
and the integers returned will run from the first to one more than the second |
| unicode |
IntintintIntegerint |
StringstrstringStringString |
a string containing the one character defined at the given Unicode code point |
Examples using standalone functions
● Test assertions that use methods asInt and asFloat:
+test test_parsetest_name?
8
assert asInt("31")actual (computed) value? evaluates to 31expected value? not run9
assert asInt("0")actual (computed) value? evaluates to 0expected value? not run10
assert asFloat("31")actual (computed) value? evaluates to 31expected value? not run11
assert asFloat("0")actual (computed) value? evaluates to 0expected value? not run12
assert asFloat("3.1")actual (computed) value? evaluates to 3.1expected value? not run13
end test
+class Test_parse(unittest.TestCase):
def test_parsetest_name?(self) -> None:
14
self.assertEqual(asInt("31")actual (computed) value?, 31expected value?) not run15
self.assertEqual(asInt("0")actual (computed) value?, 0expected value?) not run16
self.assertEqual(asFloat("31")actual (computed) value?, 31expected value?) not run17
self.assertEqual(asFloat("0")actual (computed) value?, 0expected value?) not run18
self.assertEqual(asFloat("3.1")actual (computed) value?, 3.1expected value?) not run19
# end test
+[TestClass] class Test_parse
[TestMethod] static void test_parsetest_name?() {
20
Assert.AreEqual(31expected value?, asInt("31")actual (computed) value?); not run21
Assert.AreEqual(0expected value?, asInt("0")actual (computed) value?); not run22
Assert.AreEqual(31expected value?, asFloat("31")actual (computed) value?); not run23
Assert.AreEqual(0expected value?, asFloat("0")actual (computed) value?); not run24
Assert.AreEqual(3.1expected value?, asFloat("3.1")actual (computed) value?); not run25
}} // end test
+<TestClass Class Test_parse
<TestMethod> Sub test_parsetest_name?()
26
Assert.AreEqual(31expected value?, asInt("31")actual (computed) value?) not run27
Assert.AreEqual(0expected value?, asInt("0")actual (computed) value?) not run28
Assert.AreEqual(31expected value?, asFloat("31")actual (computed) value?) not run29
Assert.AreEqual(0expected value?, asFloat("0")actual (computed) value?) not run30
Assert.AreEqual(3.1expected value?, asFloat("3.1")actual (computed) value?) not run31
End Sub
End Class
+class Test_parse {
@Test static void test_parsetest_name?() {
32
assertEquals(31expected value?, asInt("31")actual (computed) value?); not run33
assertEquals(0expected value?, asInt("0")actual (computed) value?); not run34
assertEquals(31expected value?, asFloat("31")actual (computed) value?); not run35
assertEquals(0expected value?, asFloat("0")actual (computed) value?); not run36
assertEquals(3.1expected value?, asFloat("3.1")actual (computed) value?); not run37
}} // end test
Notes
- Any string that parses as an
IntintintIntegerint will also parse as a FloatfloatdoubleDoubledouble.
- When validating user input,it may be easier to use the various input methods .
● Using method unicode:
print(unicode(0x2665))print(unicode(0x2665))print(unicode(0x2665))print(unicode(&H2665))print(unicode(0x2665)) | ⟶ | ♥ |
● Print every second item in a ListlistListListList:
+main
38
variable numbersname? set to ["zero", "one", "two", "three", "four", "five", "six"]value or expression?39
+for nitem? in rangeInSteps(0, numbers.length() + 1, 2)source?
40
print(numbers[n]value or expression?)41
end for
end main
+def main() -> None:
42
numbersname? = ["zero", "one", "two", "three", "four", "five", "six"]value or expression? # variable definition43
+for nitem? in rangeInSteps(0, numbers.length() + 1, 2)source?:
44
print(numbers[n]value or expression?)45
# end for
# end main
+static void main() {
46
var numbersname? = new [] {"zero", "one", "two", "three", "four", "five", "six"}value or expression?;47
+foreach (var nitem? in rangeInSteps(0, numbers.length() + 1, 2)source?) {
48
Console.WriteLine(numbers[n]value or expression?); // print statement49
} // end foreach
} // end main
+Sub main()
50
Dim numbersname? = {"zero", "one", "two", "three", "four", "five", "six"}value or expression? ' variable definition51
+For Each nitem? In rangeInSteps(0, numbers.length() + 1, 2)source?
52
Console.WriteLine(numbers(n)value or expression?) ' print statement53
Next n
End Sub
+static void main() {
54
var numbersname? = list("zero", "one", "two", "three", "four", "five", "six")value or expression?;55
+foreach (var nitem? in rangeInSteps(0, numbers.length() + 1, 2)source?) {
56
System.out.println(numbers[n]value or expression?); // print statement57
} // end foreach
} // end main
● Using the Higher-order Function filter to print the prime numbers less than a given limit:
+main
1
print(primesFromList(range(2, 100))value or expression?)2
end main
+function primesFromListname?(li as List<of Int>parameter definitions?) returns List<of Int>Type?
3
#
return if_(li.length() is 0, li, [li.head()].withAppendList(primesFromList(li.tail().filter(lambda n as Int => (n mod li.head()) > 0))))value or expression?4
end function
+def main() -> None:
1
print(primesFromList(range(2, 100))value or expression?)2
# end main
+def primesFromListname?(li: list[int]parameter definitions?) -> list[int]Type?:
# function3
#
return if_(li.length() == 0, li, [li.head()].withAppendList(primesFromList(li.tail().filter(lambda n: int: (n % li.head()) > 0))))value or expression?4
# end function
main()
+static void main() {
1
Console.WriteLine(primesFromList(range(2, 100))value or expression?); // print statement2
} // end main
+static List<int>Type? primesFromListname?(List<int> liparameter definitions?) {
// function3
//
return if_(li.length() == 0, li, new [] {li.head()}.withAppendList(primesFromList(li.tail().filter(int n => (n % li.head()) > 0))))value or expression?;4
} // end function
+Sub main()
1
Console.WriteLine(primesFromList(range(2, 100))value or expression?) ' print statement2
End Sub
+Function primesFromListname?(li As List(Of Integer)parameter definitions?) As List(Of Integer)Type?
3
'
Return if_(li.length() = 0, li, {li.head()}.withAppendList(primesFromList(li.tail().filter(Function (n As Integer) (n Mod li.head()) > 0))))value or expression?4
End Function
public class Global {
+static void main() {
1
System.out.println(primesFromList(range(2, 100))value or expression?); // print statement2
} // end main
+static List<int>Type? primesFromListname?(List<int> liparameter definitions?) {
// function3
//
return if_(li.length() == 0, li, list(li.head()).withAppendList(primesFromList(li.tail().filter((int n) -> (n % li.head()) > 0))))value or expression?;4
} // end function
}
// end Global
Maths functions
All the maths functions expect FloatfloatdoubleDoubledouble arguments, but IntintintIntegerint arguments are accepted.
They all return a value of type FloatfloatdoubleDoubledouble, except for divAsInt which returns an IntintintIntegerint.
| function | argument type | input unit | returns | output unit |
| abs | FloatfloatdoubleDoubledouble | | absolute value of the input | |
| divAsFloat | FloatfloatdoubleDoubledouble, FloatfloatdoubleDoubledouble | | first input value divided by second input value | |
| divAsInt | FloatfloatdoubleDoubledouble, FloatfloatdoubleDoubledouble | | first input value divided by second input value and result rounded down to integer | |
| pow | FloatfloatdoubleDoubledouble, FloatfloatdoubleDoubledouble | | result of raising first input to the power of the second | |
| sqrt | FloatfloatdoubleDoubledouble | | positive square root of the input | |
| exp |
FloatfloatdoubleDoubledouble |
|
𝑒𝑥 where 𝑥 is the argument and 𝑒 is Euler's number 2.718281828459045.. the base of natural logarithms |
|
| logE | FloatfloatdoubleDoubledouble | | natural logarithm of the input | |
| log10 | FloatfloatdoubleDoubledouble | | base-10 logarithm of the input | |
| log2 | FloatfloatdoubleDoubledouble | | base-2 logarithm of the input | |
| sin | FloatfloatdoubleDoubledouble | radians | sine of the input | |
| cos | FloatfloatdoubleDoubledouble | radians | cosine of the input | |
| tan | FloatfloatdoubleDoubledouble | radians | tangent of the input | |
| asin | FloatfloatdoubleDoubledouble | | arcsine of the input | radians |
| acos | FloatfloatdoubleDoubledouble | | arccosine of the input | radians |
| atan | FloatfloatdoubleDoubledouble | | arctangent of the input | radians |
| radians | FloatfloatdoubleDoubledouble | degrees | converts input from degrees to radians | radians |
| degrees | FloatfloatdoubleDoubledouble | radians | converts input from radians to degrees | degrees |
Examples of some maths functions and constants being tested:
+test test_mathstest_name?
5
assert piactual (computed) value? evaluates to 3.141592653589793expected value? not run6
assert abs(-3.7)actual (computed) value? evaluates to 3.7expected value? not run7
assert pow(2, 10)actual (computed) value? evaluates to 1024expected value? not run8
assert sqrt(2).round(3)actual (computed) value? evaluates to 1.414expected value? not run9
assert asin(0.5).round(3)actual (computed) value? evaluates to 0.524expected value? not run10
assert acos(0.5).round(3)actual (computed) value? evaluates to 1.047expected value? not run11
assert atan(1).round(2)actual (computed) value? evaluates to 0.79expected value? not run12
assert sin(pi/6).round(2)actual (computed) value? evaluates to 0.5expected value? not run13
assert cos(pi/4).round(3)actual (computed) value? evaluates to 0.707expected value? not run14
assert tan(pi/4).round(2)actual (computed) value? evaluates to 1expected value? not run15
assert exp(2).round(3)actual (computed) value? evaluates to 7.389expected value? not run16
assert logE(7.389).round(2)actual (computed) value? evaluates to 2expected value? not run17
assert log10(1000)actual (computed) value? evaluates to 3expected value? not run18
assert log2(65536)actual (computed) value? evaluates to 16expected value? not run19
assert log2(0x10000)actual (computed) value? evaluates to 16expected value? not run20
end test
+class Test_maths(unittest.TestCase):
def test_mathstest_name?(self) -> None:
21
self.assertEqual(piactual (computed) value?, 3.141592653589793expected value?) not run22
self.assertEqual(abs(-3.7)actual (computed) value?, 3.7expected value?) not run23
self.assertEqual(pow(2, 10)actual (computed) value?, 1024expected value?) not run24
self.assertEqual(sqrt(2).round(3)actual (computed) value?, 1.414expected value?) not run25
self.assertEqual(asin(0.5).round(3)actual (computed) value?, 0.524expected value?) not run26
self.assertEqual(acos(0.5).round(3)actual (computed) value?, 1.047expected value?) not run27
self.assertEqual(atan(1).round(2)actual (computed) value?, 0.79expected value?) not run28
self.assertEqual(sin(pi/6).round(2)actual (computed) value?, 0.5expected value?) not run29
self.assertEqual(cos(pi/4).round(3)actual (computed) value?, 0.707expected value?) not run30
self.assertEqual(tan(pi/4).round(2)actual (computed) value?, 1expected value?) not run31
self.assertEqual(exp(2).round(3)actual (computed) value?, 7.389expected value?) not run32
self.assertEqual(logE(7.389).round(2)actual (computed) value?, 2expected value?) not run33
self.assertEqual(log10(1000)actual (computed) value?, 3expected value?) not run34
self.assertEqual(log2(65536)actual (computed) value?, 16expected value?) not run35
self.assertEqual(log2(0x10000)actual (computed) value?, 16expected value?) not run36
# end test
+[TestClass] class Test_maths
[TestMethod] static void test_mathstest_name?() {
37
Assert.AreEqual(3.141592653589793expected value?, piactual (computed) value?); not run38
Assert.AreEqual(3.7expected value?, abs(-3.7)actual (computed) value?); not run39
Assert.AreEqual(1024expected value?, pow(2, 10)actual (computed) value?); not run40
Assert.AreEqual(1.414expected value?, sqrt(2).round(3)actual (computed) value?); not run41
Assert.AreEqual(0.524expected value?, asin(0.5).round(3)actual (computed) value?); not run42
Assert.AreEqual(1.047expected value?, acos(0.5).round(3)actual (computed) value?); not run43
Assert.AreEqual(0.79expected value?, atan(1).round(2)actual (computed) value?); not run44
Assert.AreEqual(0.5expected value?, sin(pi/6).round(2)actual (computed) value?); not run45
Assert.AreEqual(0.707expected value?, cos(pi/4).round(3)actual (computed) value?); not run46
Assert.AreEqual(1expected value?, tan(pi/4).round(2)actual (computed) value?); not run47
Assert.AreEqual(7.389expected value?, exp(2).round(3)actual (computed) value?); not run48
Assert.AreEqual(2expected value?, logE(7.389).round(2)actual (computed) value?); not run49
Assert.AreEqual(3expected value?, log10(1000)actual (computed) value?); not run50
Assert.AreEqual(16expected value?, log2(65536)actual (computed) value?); not run51
Assert.AreEqual(16expected value?, log2(0x10000)actual (computed) value?); not run52
}} // end test
+<TestClass Class Test_maths
<TestMethod> Sub test_mathstest_name?()
53
Assert.AreEqual(3.141592653589793expected value?, piactual (computed) value?) not run54
Assert.AreEqual(3.7expected value?, abs(-3.7)actual (computed) value?) not run55
Assert.AreEqual(1024expected value?, pow(2, 10)actual (computed) value?) not run56
Assert.AreEqual(1.414expected value?, sqrt(2).round(3)actual (computed) value?) not run57
Assert.AreEqual(0.524expected value?, asin(0.5).round(3)actual (computed) value?) not run58
Assert.AreEqual(1.047expected value?, acos(0.5).round(3)actual (computed) value?) not run59
Assert.AreEqual(0.79expected value?, atan(1).round(2)actual (computed) value?) not run60
Assert.AreEqual(0.5expected value?, sin(pi/6).round(2)actual (computed) value?) not run61
Assert.AreEqual(0.707expected value?, cos(pi/4).round(3)actual (computed) value?) not run62
Assert.AreEqual(1expected value?, tan(pi/4).round(2)actual (computed) value?) not run63
Assert.AreEqual(7.389expected value?, exp(2).round(3)actual (computed) value?) not run64
Assert.AreEqual(2expected value?, logE(7.389).round(2)actual (computed) value?) not run65
Assert.AreEqual(3expected value?, log10(1000)actual (computed) value?) not run66
Assert.AreEqual(16expected value?, log2(65536)actual (computed) value?) not run67
Assert.AreEqual(16expected value?, log2(&H10000)actual (computed) value?) not run68
End Sub
End Class
+class Test_maths {
@Test static void test_mathstest_name?() {
69
assertEquals(3.141592653589793expected value?, piactual (computed) value?); not run70
assertEquals(3.7expected value?, abs(-3.7)actual (computed) value?); not run71
assertEquals(1024expected value?, pow(2, 10)actual (computed) value?); not run72
assertEquals(1.414expected value?, sqrt(2).round(3)actual (computed) value?); not run73
assertEquals(0.524expected value?, asin(0.5).round(3)actual (computed) value?); not run74
assertEquals(1.047expected value?, acos(0.5).round(3)actual (computed) value?); not run75
assertEquals(0.79expected value?, atan(1).round(2)actual (computed) value?); not run76
assertEquals(0.5expected value?, sin(pi/6).round(2)actual (computed) value?); not run77
assertEquals(0.707expected value?, cos(pi/4).round(3)actual (computed) value?); not run78
assertEquals(1expected value?, tan(pi/4).round(2)actual (computed) value?); not run79
assertEquals(7.389expected value?, exp(2).round(3)actual (computed) value?); not run80
assertEquals(2expected value?, logE(7.389).round(2)actual (computed) value?); not run81
assertEquals(3expected value?, log10(1000)actual (computed) value?); not run82
assertEquals(16expected value?, log2(65536)actual (computed) value?); not run83
assertEquals(16expected value?, log2(0x10000)actual (computed) value?); not run84
}} // end test
Bitwise functions
These functions take in an integer value, and manipulate the bit representation of that value.
| function |
argument types |
return type |
returns |
| bitAnd |
IntintintIntegerint, IntintintIntegerint |
IntintintIntegerint |
integer whose binary representation is the bitwise AND of the inputs |
| bitOr |
IntintintIntegerint, IntintintIntegerint |
IntintintIntegerint |
integer whose binary representation is the bitwise OR of the inputs |
| bitNot |
IntintintIntegerint |
IntintintIntegerint |
integer whose binary representation is the bitwise complement of the input |
| bitXor |
IntintintIntegerint, IntintintIntegerint |
IntintintIntegerint |
integer whose binary representation is the bitwise XOR of the inputs |
| bitShiftL |
IntintintIntegerint, IntintintIntegerint |
IntintintIntegerint |
integer bit shifted to the left by the value of the second argument, i.e. multiplied by 2 to the power of the second argument |
| bitShiftR |
IntintintIntegerint, IntintintIntegerint |
IntintintIntegerint |
integer bit shifted to the right by the value of the second argument, i.e. divided by 2 to the power of the second argument |
Examples of the bitwise functions being tested
● Examples of the bitwise functions being tested
+test test_bitwisetest_name?
85
variable aname? set to 13value or expression?86
assert aactual (computed) value? evaluates to 0xdexpected value? not run87
assert aactual (computed) value? evaluates to 0b1101expected value? not run88
assert a.asBinary()actual (computed) value? evaluates to "1101"expected value? not run89
variable bname? set to 30value or expression?90
assert bactual (computed) value? evaluates to 0b11110expected value? not run91
assert bitAnd(a, b)actual (computed) value? evaluates to 0b1100expected value? not run92
variable aobname? set to bitOr(a, b)value or expression?93
assert aobactual (computed) value? evaluates to 0b11111expected value? not run94
variable axbname? set to bitXor(a, b)value or expression?95
assert axbactual (computed) value? evaluates to 0b10011expected value? not run96
variable notaname? set to bitNot(a)value or expression?97
assert notaactual (computed) value? evaluates to -14expected value? not run98
variable aLname? set to bitShiftL(a, 2)value or expression?99
assert aLactual (computed) value? evaluates to 0b110100expected value? not run100
assert bitShiftR(a, 2)actual (computed) value? evaluates to 0b11expected value? not run101
end test
+class Test_bitwise(unittest.TestCase):
def test_bitwisetest_name?(self) -> None:
102
aname? = 13value or expression? # variable definition103
self.assertEqual(aactual (computed) value?, 0xdexpected value?) not run104
self.assertEqual(aactual (computed) value?, 0b1101expected value?) not run105
self.assertEqual(a.asBinary()actual (computed) value?, "1101"expected value?) not run106
bname? = 30value or expression? # variable definition107
self.assertEqual(bactual (computed) value?, 0b11110expected value?) not run108
self.assertEqual(bitAnd(a, b)actual (computed) value?, 0b1100expected value?) not run109
aobname? = bitOr(a, b)value or expression? # variable definition110
self.assertEqual(aobactual (computed) value?, 0b11111expected value?) not run111
axbname? = bitXor(a, b)value or expression? # variable definition112
self.assertEqual(axbactual (computed) value?, 0b10011expected value?) not run113
notaname? = bitNot(a)value or expression? # variable definition114
self.assertEqual(notaactual (computed) value?, -14expected value?) not run115
aLname? = bitShiftL(a, 2)value or expression? # variable definition116
self.assertEqual(aLactual (computed) value?, 0b110100expected value?) not run117
self.assertEqual(bitShiftR(a, 2)actual (computed) value?, 0b11expected value?) not run118
# end test
+[TestClass] class Test_bitwise
[TestMethod] static void test_bitwisetest_name?() {
119
var aname? = 13value or expression?;120
Assert.AreEqual(0xdexpected value?, aactual (computed) value?); not run121
Assert.AreEqual(0b1101expected value?, aactual (computed) value?); not run122
Assert.AreEqual("1101"expected value?, a.asBinary()actual (computed) value?); not run123
var bname? = 30value or expression?;124
Assert.AreEqual(0b11110expected value?, bactual (computed) value?); not run125
Assert.AreEqual(0b1100expected value?, bitAnd(a, b)actual (computed) value?); not run126
var aobname? = bitOr(a, b)value or expression?;127
Assert.AreEqual(0b11111expected value?, aobactual (computed) value?); not run128
var axbname? = bitXor(a, b)value or expression?;129
Assert.AreEqual(0b10011expected value?, axbactual (computed) value?); not run130
var notaname? = bitNot(a)value or expression?;131
Assert.AreEqual(-14expected value?, notaactual (computed) value?); not run132
var aLname? = bitShiftL(a, 2)value or expression?;133
Assert.AreEqual(0b110100expected value?, aLactual (computed) value?); not run134
Assert.AreEqual(0b11expected value?, bitShiftR(a, 2)actual (computed) value?); not run135
}} // end test
+<TestClass Class Test_bitwise
<TestMethod> Sub test_bitwisetest_name?()
136
Dim aname? = 13value or expression? ' variable definition137
Assert.AreEqual(&Hdexpected value?, aactual (computed) value?) not run138
Assert.AreEqual(&B1101expected value?, aactual (computed) value?) not run139
Assert.AreEqual("1101"expected value?, a.asBinary()actual (computed) value?) not run140
Dim bname? = 30value or expression? ' variable definition141
Assert.AreEqual(&B11110expected value?, bactual (computed) value?) not run142
Assert.AreEqual(&B1100expected value?, bitAnd(a, b)actual (computed) value?) not run143
Dim aobname? = bitOr(a, b)value or expression? ' variable definition144
Assert.AreEqual(&B11111expected value?, aobactual (computed) value?) not run145
Dim axbname? = bitXor(a, b)value or expression? ' variable definition146
Assert.AreEqual(&B10011expected value?, axbactual (computed) value?) not run147
Dim notaname? = bitNot(a)value or expression? ' variable definition148
Assert.AreEqual(-14expected value?, notaactual (computed) value?) not run149
Dim aLname? = bitShiftL(a, 2)value or expression? ' variable definition150
Assert.AreEqual(&B110100expected value?, aLactual (computed) value?) not run151
Assert.AreEqual(&B11expected value?, bitShiftR(a, 2)actual (computed) value?) not run152
End Sub
End Class
+class Test_bitwise {
@Test static void test_bitwisetest_name?() {
153
var aname? = 13value or expression?;154
assertEquals(0xdexpected value?, aactual (computed) value?); not run155
assertEquals(0b1101expected value?, aactual (computed) value?); not run156
assertEquals("1101"expected value?, a.asBinary()actual (computed) value?); not run157
var bname? = 30value or expression?;158
assertEquals(0b11110expected value?, bactual (computed) value?); not run159
assertEquals(0b1100expected value?, bitAnd(a, b)actual (computed) value?); not run160
var aobname? = bitOr(a, b)value or expression?;161
assertEquals(0b11111expected value?, aobactual (computed) value?); not run162
var axbname? = bitXor(a, b)value or expression?;163
assertEquals(0b10011expected value?, axbactual (computed) value?); not run164
var notaname? = bitNot(a)value or expression?;165
assertEquals(-14expected value?, notaactual (computed) value?); not run166
var aLname? = bitShiftL(a, 2)value or expression?;167
assertEquals(0b110100expected value?, aLactual (computed) value?); not run168
assertEquals(0b11expected value?, bitShiftR(a, 2)actual (computed) value?); not run169
}} // end test
The result of bitNot(aaaaa) being -14-14-14-14-14 , when a is 1313131313, might be a surprise. But this is because the bitwise functions assume that the arguments are represented as 32-bit signed binary integers. So 13 is represented as
0000000000000000000000000000110100000000000000000000000000001101000000000000000000000000000011010000000000000000000000000000110100000000000000000000000000001101, and applying bitNot gives
1111111111111111111111111111001011111111111111111111111111110010111111111111111111111111111100101111111111111111111111111111001011111111111111111111111111110010which is the value -14-14-14-14-14in signed two's complement format,
the left-most bit being the sign (00000 positive, 11111 negative).
RegExp functions
Elan's regular expressions are modelled on those of JavaScript, including the syntax for literal regular expressions. See, for example this Guide to Regular Expressions .
More functions for using regular expressions will be added in a future release of Elan. For now:
The method matchesRegExp is applied to a StringstrstringStringString using dot syntax and requires a RegExpRegExpRegExpRegExpRegExp parameter specified as a literal or as variable. It returns a BooleanboolboolBooleanboolean. For example:
+test test_matchesRegExptest_name?
170
variable s1name? set to "hello"value or expression?171
variable s2name? set to "World"value or expression?172
variable rname? set to /^[a-z]*$/value or expression?173
assert s1.matchesRegExp(r)actual (computed) value? evaluates to trueexpected value? not run174
assert s2.matchesRegExp(r)actual (computed) value? evaluates to falseexpected value? not run175
end test
+class Test_matchesRegExp(unittest.TestCase):
def test_matchesRegExptest_name?(self) -> None:
176
s1name? = "hello"value or expression? # variable definition177
s2name? = "World"value or expression? # variable definition178
rname? = /^[a-z]*$/value or expression? # variable definition179
self.assertEqual(s1.matchesRegExp(r)actual (computed) value?, Trueexpected value?) not run180
self.assertEqual(s2.matchesRegExp(r)actual (computed) value?, Falseexpected value?) not run181
# end test
+[TestClass] class Test_matchesRegExp
[TestMethod] static void test_matchesRegExptest_name?() {
182
var s1name? = "hello"value or expression?;183
var s2name? = "World"value or expression?;184
var rname? = /^[a-z]*$/value or expression?;185
Assert.AreEqual(trueexpected value?, s1.matchesRegExp(r)actual (computed) value?); not run186
Assert.AreEqual(falseexpected value?, s2.matchesRegExp(r)actual (computed) value?); not run187
}} // end test
+<TestClass Class Test_matchesRegExp
<TestMethod> Sub test_matchesRegExptest_name?()
188
Dim s1name? = "hello"value or expression? ' variable definition189
Dim s2name? = "World"value or expression? ' variable definition190
Dim rname? = /^(a-z)*$/value or expression? ' variable definition191
Assert.AreEqual(Trueexpected value?, s1.matchesRegExp(r)actual (computed) value?) not run192
Assert.AreEqual(Falseexpected value?, s2.matchesRegExp(r)actual (computed) value?) not run193
End Sub
End Class
+class Test_matchesRegExp {
@Test static void test_matchesRegExptest_name?() {
194
var s1name? = "hello"value or expression?;195
var s2name? = "World"value or expression?;196
var rname? = /^[a-z]*$/value or expression?;197
assertEquals(trueexpected value?, s1.matchesRegExp(r)actual (computed) value?); not run198
assertEquals(falseexpected value?, s2.matchesRegExp(r)actual (computed) value?); not run199
}} // end test
You can convert a valid string without /..//..//..//..//../ delimiters to a RegExpRegExpRegExpRegExpRegExp using function asRegExp:
+test test_matchesRegExptest_name?
200
variable s1name? set to "hello"value or expression?201
variable s2name? set to "World"value or expression?202
variable rname? set to "^[a-z]*$".asRegExp()value or expression?203
assert s1.matchesRegExp(r)actual (computed) value? evaluates to trueexpected value? not run204
assert s2.matchesRegExp(r)actual (computed) value? evaluates to falseexpected value? not run205
end test
+class Test_matchesRegExp(unittest.TestCase):
def test_matchesRegExptest_name?(self) -> None:
206
s1name? = "hello"value or expression? # variable definition207
s2name? = "World"value or expression? # variable definition208
rname? = "^[a-z]*$".asRegExp()value or expression? # variable definition209
self.assertEqual(s1.matchesRegExp(r)actual (computed) value?, Trueexpected value?) not run210
self.assertEqual(s2.matchesRegExp(r)actual (computed) value?, Falseexpected value?) not run211
# end test
+[TestClass] class Test_matchesRegExp
[TestMethod] static void test_matchesRegExptest_name?() {
212
var s1name? = "hello"value or expression?;213
var s2name? = "World"value or expression?;214
var rname? = "^[a-z]*$".asRegExp()value or expression?;215
Assert.AreEqual(trueexpected value?, s1.matchesRegExp(r)actual (computed) value?); not run216
Assert.AreEqual(falseexpected value?, s2.matchesRegExp(r)actual (computed) value?); not run217
}} // end test
+<TestClass Class Test_matchesRegExp
<TestMethod> Sub test_matchesRegExptest_name?()
218
Dim s1name? = "hello"value or expression? ' variable definition219
Dim s2name? = "World"value or expression? ' variable definition220
Dim rname? = "^(a-z)*$".asRegExp()value or expression? ' variable definition221
Assert.AreEqual(Trueexpected value?, s1.matchesRegExp(r)actual (computed) value?) not run222
Assert.AreEqual(Falseexpected value?, s2.matchesRegExp(r)actual (computed) value?) not run223
End Sub
End Class
+class Test_matchesRegExp {
@Test static void test_matchesRegExptest_name?() {
224
var s1name? = "hello"value or expression?;225
var s2name? = "World"value or expression?;226
var rname? = "^[a-z]*$".asRegExp()value or expression?;227
assertEquals(trueexpected value?, s1.matchesRegExp(r)actual (computed) value?); not run228
assertEquals(falseexpected value?, s2.matchesRegExp(r)actual (computed) value?); not run229
}} // end test
Although it is recommended that literal regular expressions are written with /..//..//..//..//../ delimiters, the ability to convert a stringstringstringstringstring allows you to input a regular expression into a running program.
System methods
System methods appear to work like functions, because:
- they may require one or more arguments to be provided
- they always return a value
- they can be used in expressions
They are not, however, pure functions because:
- they may have a dependency on data that is not provided in an argument
- they may generate side effects, such as changing the screen display or writing to a file
Because of these properties, system methods may be used only within the main routine or a procedure.
They may not be used inside a function that you have defined, because to do so would prevent the function from being pure.
You cannot write a system method yourself.
Input/output
Clock
Method clock returns the current value of the system clock.
This can be useful for measuring elapsed time by comparing the values returned by two calls.
system method |
argument types |
return types |
returns |
| clock |
(none) |
IntintintIntegerint |
the current value (in milliseconds) of the system clock |
Random methods
Methods random and randint cannot be used in a function because
of their dependence on external factors, i.e. they are subject to side effects.
To obtain random numbers within a function, use a variable of type RandomRandomRandomRandomRandom .
system method |
argument types |
return types |
returns |
| random |
(none) |
FloatfloatdoubleDoubledouble |
a random number in the range [0..1] |
| randint |
IntintintIntegerint, IntintintIntegerint |
IntintintIntegerint |
a random number in the (inclusive) range between the two arguments |
Higher-order Functions (HoFs)
A higher-order Function (HoF) is one that takes in a reference to another function as a parameter. (Strictly speaking, a HoF may also be a function that returns another function,
but Elan does not currently support that pattern.)
Standard HoFs
The standard library contains several HoFs that are widely recognised and used within functional programming, namely:
filter ,
map and
reduce ,
and also provides:
sumBy ,
maxBy ,
minBy and
orderBy .
You cannot define your own Higher-order Functions.
Library functions that process Lists
These dot methods may be called on any ListlistListListList or StringstrstringStringString. As Higher-order Functions they take either a lambdalambdalambdalambdalambda or a function reference as one of their arguments.
These are not yet fully documented but, for readers familiar with HoFs from another programming language, some examples are shown below.
filter
You give a ListlistListListList to the Higher-order Function filter in order to return a new ListlistListListList containing a subset of items.
The subset is chosen by a lambdalambdalambdalambdalambda that tests ListlistListListList item values and returns a Boolean to specify filtering in or out.
Example using filter
● Example from demo program pathfinder in which filter applies the lambdalambdalambdalambdalambda to the nodesnodesnodesnodesnodes (of class NodeNodeNodeNodeNode) to find one that contains ppppp (of class PointPointPointPointPoint):
+function getNodeForname?(p as Pointparameter definitions?) returns NodeType?
230
variable matchesname? set to this.nodes.filter(lambda n as Node => n.point.equals(p))value or expression?231
return if_(matches.length() is 1, matches.head(), emptyNode())value or expression?232
end function
+def getNodeForname?(p: Pointparameter definitions?) -> NodeType?:
# function233
matchesname? = self.nodes.filter(lambda n: Node: n.point.equals(p))value or expression? # variable definition234
return if_(matches.length() == 1, matches.head(), emptyNode())value or expression?235
# end function
+static NodeType? getNodeForname?(Point pparameter definitions?) {
// function236
var matchesname? = this.nodes.filter(Node n => n.point.equals(p))value or expression?;237
return if_(matches.length() == 1, matches.head(), emptyNode())value or expression?;238
} // end function
+Function getNodeForname?(p As Pointparameter definitions?) As NodeType?
239
Dim matchesname? = Me.nodes.filter(Function (n As Node) n.point.equals(p))value or expression? ' variable definition240
Return if_(matches.length() = 1, matches.head(), emptyNode())value or expression?241
End Function
+static NodeType? getNodeForname?(Point pparameter definitions?) {
// function242
var matchesname? = this.nodes.filter((Node n) -> n.point.equals(p))value or expression?;243
return if_(matches.length() == 1, matches.head(), emptyNode())value or expression?;244
} // end function
map
The function map is used to apply a function to every item in a ListlistListListList, and return a new ListlistListListList.
The function to be applied is usually specified as a lambdalambdalambdalambdalambda having a single argument of the type of the ListlistListListList's items, as in these examples:
Examples using map
● To cube each integer value in a ListlistListListList:
+main
245
variable liname? set to [1, 2, 3, 4, 5]value or expression?246
print(li.map(lambda n as Int => pow(n, 3))value or expression?)247
end main
+def main() -> None:
248
liname? = [1, 2, 3, 4, 5]value or expression? # variable definition249
print(li.map(lambda n: int: pow(n, 3))value or expression?)250
# end main
+static void main() {
251
var liname? = new [] {1, 2, 3, 4, 5}value or expression?;252
Console.WriteLine(li.map(int n => pow(n, 3))value or expression?); // print statement253
} // end main
+Sub main()
254
Dim liname? = {1, 2, 3, 4, 5}value or expression? ' variable definition255
Console.WriteLine(li.map(Function (n As Integer) pow(n, 3))value or expression?) ' print statement256
End Sub
+static void main() {
257
var liname? = list(1, 2, 3, 4, 5)value or expression?;258
System.out.println(li.map((int n) -> pow(n, 3))value or expression?); // print statement259
} // end main
|
⟶ |
[1, 8, 27, 125][1, 8, 27, 125]new [] {1, 8, 27, 125}{1, 8, 27, 125}list(1, 8, 27, 125) |
● To change each string in a ListlistListListList to upper case:
+main
260
variable namesname? set to ["Tom", "Dick", "Harriet"]value or expression?261
print(names.map(lambda s as String => s.upperCase())value or expression?)262
end main
+def main() -> None:
263
namesname? = ["Tom", "Dick", "Harriet"]value or expression? # variable definition264
print(names.map(lambda s: str: s.upperCase())value or expression?)265
# end main
+static void main() {
266
var namesname? = new [] {"Tom", "Dick", "Harriet"}value or expression?;267
Console.WriteLine(names.map(string s => s.upperCase())value or expression?); // print statement268
} // end main
+Sub main()
269
Dim namesname? = {"Tom", "Dick", "Harriet"}value or expression? ' variable definition270
Console.WriteLine(names.map(Function (s As String) s.upperCase())value or expression?) ' print statement271
End Sub
+static void main() {
272
var namesname? = list("Tom", "Dick", "Harriet")value or expression?;273
System.out.println(names.map((String s) -> s.upperCase())value or expression?); // print statement274
} // end main
|
⟶ |
[TOM, DICK, HARRIET] |
● To reverse each string in the ListlistListListList of names using the function reverse:
+main
1
print(names.map(lambda s as String => reverse(s))value or expression?)2
end main
+function reversename?(s as Stringparameter definitions?) returns StringType?
3
variable sReturnname? set to ""value or expression?4
+for chitem? in ssource?
5
assign sReturnvariableName? to ch + sReturnvalue or expression?6
end for
return sReturnvalue or expression?7
end function
+def main() -> None:
1
print(names.map(lambda s: str: reverse(s))value or expression?)2
# end main
+def reversename?(s: strparameter definitions?) -> strType?:
# function3
sReturnname? = ""value or expression? # variable definition4
+for chitem? in ssource?:
5
sReturnvariableName? = ch + sReturnvalue or expression? # assignment6
# end for
return sReturnvalue or expression?7
# end function
main()
+static void main() {
1
Console.WriteLine(names.map(string s => reverse(s))value or expression?); // print statement2
} // end main
+static stringType? reversename?(string sparameter definitions?) {
// function3
var sReturnname? = ""value or expression?;4
+foreach (var chitem? in ssource?) {
5
sReturnvariableName? = ch + sReturnvalue or expression?; // assignment6
} // end foreach
return sReturnvalue or expression?;7
} // end function
+Sub main()
1
Console.WriteLine(names.map(Function (s As String) reverse(s))value or expression?) ' print statement2
End Sub
+Function reversename?(s As Stringparameter definitions?) As StringType?
3
Dim sReturnname? = ""value or expression? ' variable definition4
+For Each chitem? In ssource?
5
sReturnvariableName? = ch + sReturnvalue or expression? ' assignment6
Next ch
Return sReturnvalue or expression?7
End Function
public class Global {
+static void main() {
1
System.out.println(names.map((String s) -> reverse(s))value or expression?); // print statement2
} // end main
+static StringType? reversename?(String sparameter definitions?) {
// function3
var sReturnname? = ""value or expression?;4
+foreach (var chitem? in ssource?) {
5
sReturnvariableName? = ch + sReturnvalue or expression?; // assignment6
} // end foreach
return sReturnvalue or expression?;7
} // end function
} // end Global
|
⟶ | [moT, kciD, teirraH] |
● And this example from demo program maze-generator:
variable nname? set to p.neighbouringPoints().map(lambda p as Point => getValue(p, g))value or expression?8
nname? = p.neighbouringPoints().map(lambda p: Point: getValue(p, g))value or expression? # variable definition9
var nname? = p.neighbouringPoints().map(Point p => getValue(p, g))value or expression?;10
Dim nname? = p.neighbouringPoints().map(Function (p As Point) getValue(p, g))value or expression? ' variable definition11
var nname? = p.neighbouringPoints().map((Point p) -> getValue(p, g))value or expression?;12
reduce
The function reduce is used to combine the items in a ListlistListListList in some way to produce a single result. This result may be of the same type as the items in the ListlistListListList, for example to:
- find the sum or sum-of-squares of a
ListlistListListList of numeric values.
- concatenate, or combine in some other way, the items from a
ListlistListListList of strings.
The result may, however, be of a different type than the items in the ListlistListListList, and may even be a data structure, for example to:
- generate a 3-tuple containing the sum, sum-of-squares, and count of numerical items,
- generate a dictionary of all the unique words in a
ListlistListListList, with the number of times each word appears in the input ListlistListListList.
Method reduce requires two arguments:
- the initial, or 'seed', value, of the type that you wish to be returned by the function specified in the second argument.
For example, if you were finding the sum of a
ListlistListListList of type FloatfloatdoubleDoubledouble, the initial seed value
would typically be 0.00.00.00.00.0. If you were creating a dictionary of words, the initial seed
value would be an empty dictionary of the correct key and value types.
- the function or
lambdalambdalambdalambdalambda to be applied, which itself requires two arguments:
- the accumulating named value, which is therefore of the same type as the initial seed value,
(This will be the return value of the function or
lambdalambdalambdalambdalambda).
- the item to which the function is applied, which is therefore of the same type
as the items in the input
ListlistListListList.
In other words, the specified function or lambdalambdalambdalambdalambda is applied to each item of the input ListlistListListList in turn, in each case passing in the current value
of the result. The function makes use of both to generate a new value for the result, replacing the current one
for application to the next item. This is best understood by looking at the examples.
Examples using reduce
● To reduce the floating point values in a ListlistListListList to their sum:
+main
13
variable nname? set to [0.1, 2, 2.5, 0.3, 5.75, 0.29]value or expression?14
print(n.reduce(0.0, lambda sum as Float, m as Float => (sum + m).round(2))value or expression?)15
end main
+def main() -> None:
16
nname? = [0.1, 2, 2.5, 0.3, 5.75, 0.29]value or expression? # variable definition17
print(n.reduce(0.0, lambda sum: float, m: float: (sum + m).round(2))value or expression?)18
# end main
+static void main() {
19
var nname? = new [] {0.1, 2, 2.5, 0.3, 5.75, 0.29}value or expression?;20
Console.WriteLine(n.reduce(0.0, double sum, double m => (sum + m).round(2))value or expression?); // print statement21
} // end main
+Sub main()
22
Dim nname? = {0.1, 2, 2.5, 0.3, 5.75, 0.29}value or expression? ' variable definition23
Console.WriteLine(n.reduce(0.0, Function (sum As Double, m As Double) (sum + m).round(2))value or expression?) ' print statement24
End Sub
+static void main() {
25
var nname? = list(0.1, 2, 2.5, 0.3, 5.75, 0.29)value or expression?;26
System.out.println(n.reduce(0.0, (double sum, double m) -> (sum + m).round(2))value or expression?); // print statement27
} // end main
|
⟶ |
10.9410.9410.9410.9410.94 |
Notes
- You usually need to round floating point values when outputting them.
- The inclusion of an integer in a
ListlistListListList of floats is valid provided it is not the first value.
● To reverse the order of items in a ListlistListListList:
+main
28
variable nname? set to [2, 3, 5, 7, 11, 13]value or expression?29
variable nRname? set to new List<of Int>()value or expression?30
variable eLname? set to new List<of Int>()value or expression?31
print(n.reduce(eL, lambda nR as List<of Int>, m as Int => nR.withPrepend(m))value or expression?)32
end main
+def main() -> None:
33
nname? = [2, 3, 5, 7, 11, 13]value or expression? # variable definition34
nRname? = list[int]()value or expression? # variable definition35
eLname? = list[int]()value or expression? # variable definition36
print(n.reduce(eL, lambda nR: list[int], m: int: nR.withPrepend(m))value or expression?)37
# end main
+static void main() {
38
var nname? = new [] {2, 3, 5, 7, 11, 13}value or expression?;39
var nRname? = new List<int>()value or expression?;40
var eLname? = new List<int>()value or expression?;41
Console.WriteLine(n.reduce(eL, List<int> nR, int m => nR.withPrepend(m))value or expression?); // print statement42
} // end main
+Sub main()
43
Dim nname? = {2, 3, 5, 7, 11, 13}value or expression? ' variable definition44
Dim nRname? = New List(Of Integer)()value or expression? ' variable definition45
Dim eLname? = New List(Of Integer)()value or expression? ' variable definition46
Console.WriteLine(n.reduce(eL, Function (nR As List(Of Integer), m As Integer) nR.withPrepend(m))value or expression?) ' print statement47
End Sub
+static void main() {
48
var nname? = list(2, 3, 5, 7, 11, 13)value or expression?;49
var nRname? = new List<int>()value or expression?;50
var eLname? = new List<int>()value or expression?;51
System.out.println(n.reduce(eL, (List<int> nR, int m) -> nR.withPrepend(m))value or expression?); // print statement52
} // end main
|
⟶ |
[13, 11, 7, 5, 3, 2][13, 11, 7, 5, 3, 2]new [] {13, 11, 7, 5, 3, 2}{13, 11, 7, 5, 3, 2}list(13, 11, 7, 5, 3, 2) |
● To reverse the order of the words in a StringstrstringStringString,
use reduce on a ListlistListListList of words (created by split and then reassembled by join):
+main
53
variable sname? set to "'Twas brillig and the slithy toves"value or expression?54
variable sRname? set to ""value or expression?55
variable eLname? set to new List<of String>()value or expression?56
assign sRvariableName? to s.split(" ").reduce(eL, lambda sR as List<of String>, word as String => sR.withPrepend(word)).join(" ")value or expression?57
print(sRvalue or expression?)58
end main
+def main() -> None:
59
sname? = "'Twas brillig and the slithy toves"value or expression? # variable definition60
sRname? = ""value or expression? # variable definition61
eLname? = list[str]()value or expression? # variable definition62
sRvariableName? = s.split(" ").reduce(eL, lambda sR: list[str], word: str: sR.withPrepend(word)).join(" ")value or expression? # assignment63
print(sRvalue or expression?)64
# end main
+static void main() {
65
var sname? = "'Twas brillig and the slithy toves"value or expression?;66
var sRname? = ""value or expression?;67
var eLname? = new List<string>()value or expression?;68
sRvariableName? = s.split(" ").reduce(eL, List<string> sR, string word => sR.withPrepend(word)).join(" ")value or expression?; // assignment69
Console.WriteLine(sRvalue or expression?); // print statement70
} // end main
+Sub main()
71
Dim sname? = "'Twas brillig and the slithy toves"value or expression? ' variable definition72
Dim sRname? = ""value or expression? ' variable definition73
Dim eLname? = New List(Of String)()value or expression? ' variable definition74
sRvariableName? = s.split(" ").reduce(eL, Function (sR As List(Of String), word As String) sR.withPrepend(word)).join(" ")value or expression? ' assignment75
Console.WriteLine(sRvalue or expression?) ' print statement76
End Sub
+static void main() {
77
var sname? = "'Twas brillig and the slithy toves"value or expression?;78
var sRname? = ""value or expression?;79
var eLname? = new List<String>()value or expression?;80
sRvariableName? = s.split(" ").reduce(eL, (List<String> sR, String word) -> sR.withPrepend(word)).join(" ")value or expression?; // assignment81
System.out.println(sRvalue or expression?); // print statement82
} // end main
|
⟶ |
"toves slithy the and brillig 'Twas""toves slithy the and brillig 'Twas""toves slithy the and brillig 'Twas""toves slithy the and brillig 'Twas""toves slithy the and brillig 'Twas" |
Note
- In these two examples on
ListlistListListLists, an empty List has to be defined for use as the first argument of reduce.
maxBy and minBy
maxBy and minBy are dot methods on a ListlistListListList.
They take a function as an argument, and return the ListlistListListList item corresponding to the maximum or minimum of the values returned by the function.
For simply finding the maximum or minimum value in a ListlistListListList, you can use
max ,
min .
Examples using maxBy and minBy
● To find in a ListlistListListList the integer that has the highest last digit:
+main
83
variable aname? set to [33, 4, 0, 92, 89, 55, 102]value or expression?84
print(a.maxBy(lambda x as Int => x mod 10)value or expression?)85
end main
+def main() -> None:
86
aname? = [33, 4, 0, 92, 89, 55, 102]value or expression? # variable definition87
print(a.maxBy(lambda x: int: x % 10)value or expression?)88
# end main
+static void main() {
89
var aname? = new [] {33, 4, 0, 92, 89, 55, 102}value or expression?;90
Console.WriteLine(a.maxBy(int x => x % 10)value or expression?); // print statement91
} // end main
+Sub main()
92
Dim aname? = {33, 4, 0, 92, 89, 55, 102}value or expression? ' variable definition93
Console.WriteLine(a.maxBy(Function (x As Integer) x Mod 10)value or expression?) ' print statement94
End Sub
+static void main() {
95
var aname? = list(33, 4, 0, 92, 89, 55, 102)value or expression?;96
System.out.println(a.maxBy((int x) -> x % 10)value or expression?); // print statement97
} // end main
|
⟶ |
8989898989 |
● To find in a ListlistListListList the the shortest string:
+main
98
variable fruitname? set to ["apple", "orange", "pear"]value or expression?99
print(fruit.minBy(lambda x as String => x.length())value or expression?)100
end main
+def main() -> None:
101
fruitname? = ["apple", "orange", "pear"]value or expression? # variable definition102
print(fruit.minBy(lambda x: str: x.length())value or expression?)103
# end main
+static void main() {
104
var fruitname? = new [] {"apple", "orange", "pear"}value or expression?;105
Console.WriteLine(fruit.minBy(string x => x.length())value or expression?); // print statement106
} // end main
+Sub main()
107
Dim fruitname? = {"apple", "orange", "pear"}value or expression? ' variable definition108
Console.WriteLine(fruit.minBy(Function (x As String) x.length())value or expression?) ' print statement109
End Sub
+static void main() {
110
var fruitname? = list("apple", "orange", "pear")value or expression?;111
System.out.println(fruit.minBy((String x) -> x.length())value or expression?); // print statement112
} // end main
|
⟶ |
pearpearpearpearpear |
sumBy
sumBy calculates the numerical sum of the items generated by the specified lambda (or named function)
which must return a floating point value. This does not mean that the ListlistListListList on which sumBy
has to be of type List<of Float>list[float]List<double>List(Of Double)List<double>. However, the lambda must process each element in a way that returns a FloatfloatdoubleDoubledouble.
Examples using sumBy
This example is taken from the Best Fit demo (offered when the paradigm is set to functional)
to calculate the various 'sigma' (sum of) terms needed to estimate the best fit line:
+function bestFitLinename?(points as List<of Point>parameter definitions?) returns (Float, Float)Type?
113
let sumXname? be points.sumBy(lambda p as Point => p.x)value or expression?114
let sumXsqname? be points.sumBy(lambda p as Point => p.x*p.x)value or expression?115
let sumYname? be points.sumBy(lambda p as Point => p.y)value or expression?116
let sumXYname? be points.sumBy(lambda p as Point => p.x*p.y)value or expression?117
let nname? be points.length()value or expression?118
let aname? be (sumY*sumXsq - sumX*sumXY)/(n*sumXsq - sumX*sumX)value or expression?119
let bname? be (n*sumXY - sumX*sumY)/(n*sumXsq - sumX*sumX)value or expression?120
return (a, b)value or expression?121
end function
+def bestFitLinename?(points: list[Point]parameter definitions?) -> tuple[float, float]Type?:
# function122
sumXname? = points.sumBy(lambda p: Point: p.x)value or expression? # let123
sumXsqname? = points.sumBy(lambda p: Point: p.x*p.x)value or expression? # let124
sumYname? = points.sumBy(lambda p: Point: p.y)value or expression? # let125
sumXYname? = points.sumBy(lambda p: Point: p.x*p.y)value or expression? # let126
nname? = points.length()value or expression? # let127
aname? = (sumY*sumXsq - sumX*sumXY)/(n*sumXsq - sumX*sumX)value or expression? # let128
bname? = (n*sumXY - sumX*sumY)/(n*sumXsq - sumX*sumX)value or expression? # let129
return (a, b)value or expression?130
# end function
+static (double, double)Type? bestFitLinename?(List<Point> pointsparameter definitions?) {
// function131
var sumXname? = points.sumBy(Point p => p.x)value or expression?; // let132
var sumXsqname? = points.sumBy(Point p => p.x*p.x)value or expression?; // let133
var sumYname? = points.sumBy(Point p => p.y)value or expression?; // let134
var sumXYname? = points.sumBy(Point p => p.x*p.y)value or expression?; // let135
var nname? = points.length()value or expression?; // let136
var aname? = (sumY*sumXsq - sumX*sumXY)/(n*sumXsq - sumX*sumX)value or expression?; // let137
var bname? = (n*sumXY - sumX*sumY)/(n*sumXsq - sumX*sumX)value or expression?; // let138
return (a, b)value or expression?;139
} // end function
+Function bestFitLinename?(points As List(Of Point)parameter definitions?) As (Double, Double)Type?
140
Dim sumXname? = points.sumBy(Function (p As Point) p.x)value or expression? ' let141
Dim sumXsqname? = points.sumBy(Function (p As Point) p.x*p.x)value or expression? ' let142
Dim sumYname? = points.sumBy(Function (p As Point) p.y)value or expression? ' let143
Dim sumXYname? = points.sumBy(Function (p As Point) p.x*p.y)value or expression? ' let144
Dim nname? = points.length()value or expression? ' let145
Dim aname? = (sumY*sumXsq - sumX*sumXY)/(n*sumXsq - sumX*sumX)value or expression? ' let146
Dim bname? = (n*sumXY - sumX*sumY)/(n*sumXsq - sumX*sumX)value or expression? ' let147
Return (a, b)value or expression?148
End Function
+static (double, double)Type? bestFitLinename?(List<Point> pointsparameter definitions?) {
// function149
var sumXname? = points.sumBy((Point p) -> p.x)value or expression?; // let150
var sumXsqname? = points.sumBy((Point p) -> p.x*p.x)value or expression?; // let151
var sumYname? = points.sumBy((Point p) -> p.y)value or expression?; // let152
var sumXYname? = points.sumBy((Point p) -> p.x*p.y)value or expression?; // let153
var nname? = points.length()value or expression?; // let154
var aname? = (sumY*sumXsq - sumX*sumXY)/(n*sumXsq - sumX*sumX)value or expression?; // let155
var bname? = (n*sumXY - sumX*sumY)/(n*sumXsq - sumX*sumX)value or expression?; // let156
return (a, b)value or expression?;157
} // end function
orderBy
orderBy takes a lambdalambdalambdalambdalambda that has two arguments of the same type as that of the ListlistListListList items to be re-ordered
and compares them, returning a Boolean value that distinguishes between less than (or greater than) for numerics and before (or after) for strings.
Examples using orderBy
● To reorder integers in a ListlistListListList, using > for ascending (you would use < for descending):
+main
158
variable numbersname? set to [27, 2, 3, 5, 7, 31, 37, 11, 23, 13, 19, 23]value or expression?159
variable orderedname? set to numbers.orderBy(lambda x as Int, y as Int => x > y)value or expression?160
print(orderedvalue or expression?)161
end main
+def main() -> None:
162
numbersname? = [27, 2, 3, 5, 7, 31, 37, 11, 23, 13, 19, 23]value or expression? # variable definition163
orderedname? = numbers.orderBy(lambda x: int, y: int: x > y)value or expression? # variable definition164
print(orderedvalue or expression?)165
# end main
+static void main() {
166
var numbersname? = new [] {27, 2, 3, 5, 7, 31, 37, 11, 23, 13, 19, 23}value or expression?;167
var orderedname? = numbers.orderBy(int x, int y => x > y)value or expression?;168
Console.WriteLine(orderedvalue or expression?); // print statement169
} // end main
+Sub main()
170
Dim numbersname? = {27, 2, 3, 5, 7, 31, 37, 11, 23, 13, 19, 23}value or expression? ' variable definition171
Dim orderedname? = numbers.orderBy(Function (x As Integer, y As Integer) x > y)value or expression? ' variable definition172
Console.WriteLine(orderedvalue or expression?) ' print statement173
End Sub
+static void main() {
174
var numbersname? = list(27, 2, 3, 5, 7, 31, 37, 11, 23, 13, 19, 23)value or expression?;175
var orderedname? = numbers.orderBy((int x, int y) -> x > y)value or expression?;176
System.out.println(orderedvalue or expression?); // print statement177
} // end main
|
⟶ |
[2, 3, 5, 7, 11, 13, 19, 23, 23, 27, 31, 37][2, 3, 5, 7, 11, 13, 19, 23, 23, 27, 31, 37]new [] {2, 3, 5, 7, 11, 13, 19, 23, 23, 27, 31, 37}{2, 3, 5, 7, 11, 13, 19, 23, 23, 27, 31, 37}list(2, 3, 5, 7, 11, 13, 19, 23, 23, 27, 31, 37) |
● To reorder strings in a ListlistListListList, using method isBefore for descending (you would use isAfter for ascending):
+main
178
variable namesname? set to ["Simon", "Pauline", "Jason", "Zelda", "Edith", "Lance", "Alice", "Paul"]value or expression?179
print(names.orderBy(lambda x as String, y as String => x.isBefore(y))value or expression?)180
end main
+def main() -> None:
181
namesname? = ["Simon", "Pauline", "Jason", "Zelda", "Edith", "Lance", "Alice", "Paul"]value or expression? # variable definition182
print(names.orderBy(lambda x: str, y: str: x.isBefore(y))value or expression?)183
# end main
+static void main() {
184
var namesname? = new [] {"Simon", "Pauline", "Jason", "Zelda", "Edith", "Lance", "Alice", "Paul"}value or expression?;185
Console.WriteLine(names.orderBy(string x, string y => x.isBefore(y))value or expression?); // print statement186
} // end main
+Sub main()
187
Dim namesname? = {"Simon", "Pauline", "Jason", "Zelda", "Edith", "Lance", "Alice", "Paul"}value or expression? ' variable definition188
Console.WriteLine(names.orderBy(Function (x As String, y As String) x.isBefore(y))value or expression?) ' print statement189
End Sub
+static void main() {
190
var namesname? = list("Simon", "Pauline", "Jason", "Zelda", "Edith", "Lance", "Alice", "Paul")value or expression?;191
System.out.println(names.orderBy((String x, String y) -> x.isBefore(y))value or expression?); // print statement192
} // end main
|
⟶ |
["Zelda", "Simon", "Pauline", "Paul", "Lance", "Jason", "Edith", "Alice"]["Zelda", "Simon", "Pauline", "Paul", "Lance", "Jason", "Edith", "Alice"]new [] {"Zelda", "Simon", "Pauline", "Paul", "Lance", "Jason", "Edith", "Alice"}{"Zelda", "Simon", "Pauline", "Paul", "Lance", "Jason", "Edith", "Alice"}list("Zelda", "Simon", "Pauline", "Paul", "Lance", "Jason", "Edith", "Alice") |
Passing a function as a reference
To use a Higher-order Function (HoF), you have to pass in a reference to a function.
This can be either a lambdalambdalambdalambdalambda or the name of a function.
It is also possible to use references to functions not in the context of HoFs.
On most occasions when you write the name of an existing function elsewhere in code your intent is to evaluate the function and, to do so, you write the name of the function followed by round brackets containing such arguments as are required by the function. When passing a function, its name is not followed by round brackets (or arguments), as in this example:
+class PupilName? inheritance?1
+constructor(parameter definitions?)
2
new code
end constructor
property mathsPercentname? as IntType?3
+function toStringname?(parameter definitions?) returns StringType?
4
return "undefined"value or expression?5
end function
end class
+main
6
variable allPupilsname? set to new List<of Pupil>()value or expression?7
variable passesname? set to allPupils.filter(passedMathsTest)value or expression?8
end main
+function passedMathsTestname?(p as Pupilparameter definitions?) returns BooleanType?
9
return p.mathsPercent > 35value or expression?10
end function
+class PupilName? inheritance?: # concrete class1
+def __init__(self: Pupil) -> None:
2
new code
# end constructor
mathsPercentname?: intType? # property3
+def toStringname?(self: Pupil) -> strType?:
# function method4
return "undefined"value or expression?5
# end function method
# end class
+def main() -> None:
6
allPupilsname? = list[Pupil]()value or expression? # variable definition7
passesname? = allPupils.filter(passedMathsTest)value or expression? # variable definition8
# end main
+def passedMathsTestname?(p: Pupilparameter definitions?) -> boolType?:
# function9
return p.mathsPercent > 35value or expression?10
# end function
main()
+class PupilName? inheritance? {1
+public Pupil(parameter definitions?) {
2
new code
} // end constructor
public intType? mathsPercentname? {get; private set;} // property3
+public stringType? toStringname?(parameter definitions?) {
// function method4
return "undefined"value or expression?;5
} // end function method
} // end class
+static void main() {
6
var allPupilsname? = new List<Pupil>()value or expression?;7
var passesname? = allPupils.filter(passedMathsTest)value or expression?;8
} // end main
+static boolType? passedMathsTestname?(Pupil pparameter definitions?) {
// function9
return p.mathsPercent > 35value or expression?;10
} // end function
+Class PupilName? inheritance?1
+Sub New(parameter definitions?)
2
new code
End Sub
Property mathsPercentname? As IntegerType?3
+Function toStringname?(parameter definitions?) As StringType?
4
Return "undefined"value or expression?5
End Function
End Class
+Sub main()
6
Dim allPupilsname? = New List(Of Pupil)()value or expression? ' variable definition7
Dim passesname? = allPupils.filter(passedMathsTest)value or expression? ' variable definition8
End Sub
+Function passedMathsTestname?(p As Pupilparameter definitions?) As BooleanType?
9
Return p.mathsPercent > 35value or expression?10
End Function
public class Global {
+class PupilName? inheritance? {1
+public Pupil(parameter definitions?) {
2
new code
} // end constructor
public intType? mathsPercentname?; // property3
+public StringType? toStringname?(parameter definitions?) {
// function method4
return "undefined"value or expression?;5
} // end function method
} // end class
+static void main() {
6
var allPupilsname? = new List<Pupil>()value or expression?;7
var passesname? = allPupils.filter(passedMathsTest)value or expression?;8
} // end main
+static booleanType? passedMathsTestname?(Pupil pparameter definitions?) {
// function9
return p.mathsPercent > 35value or expression?;10
} // end function
}
// end Global
System constants
System constants are unlike values that you define in your program constant ,
in that they are mutable named values, though it would be poor practice to change them.
String constants
These constants are of use when the characters { } and " are required within a string.
| name | type | value |
openBraceopenBraceopenBraceopenBraceopenBrace |
StringstrstringStringString |
{ |
closeBracecloseBracecloseBracecloseBracecloseBrace |
StringstrstringStringString |
} |
quotesquotesquotesquotesquotes |
StringstrstringStringString |
" |
Maths constant
| name | type | value |
pipipipipi |
FloatfloatdoubleDoubledouble |
𝜋 = 3.141592653589793.. |
Boolean constants
Colour constants
| colour | | decimal | decimal
| hexadecimal |
| name | | integer | R G B | 0xrrggbb |
blackblackblackblackblack | ◼ | 0 | 0 0 0 | 0x0000000x0000000x000000&H0000000x000000 |
whitewhitewhitewhitewhite | ◼ | 16777215 | 255 255 255 | 0xffffff0xffffff0xffffff&Hffffff0xffffff |
redredredredred | ◼ | 16711680 | 255 0 0 | 0xff00000xff00000xff0000&Hff00000xff0000 |
greengreengreengreengreen | ◼ | 32768 | 0 128 0 | 0x0080000x0080000x008000&H0080000x008000 |
blueblueblueblueblue | ◼ | 255 | 0 0 255 | 0x0000ff0x0000ff0x0000ff&H0000ff0x0000ff |
yellowyellowyellowyellowyellow | ◼ | 16776960 | 255 255 0 | 0xffff000xffff000xffff00&Hffff000xffff00 |
brownbrownbrownbrownbrown | ◼ | 10824234 | 165 42 42 | 0xa52a2a0xa52a2a0xa52a2a&Ha52a2a0xa52a2a |
greygreygreygreygrey | ◼ | 8421504 | 128 128 128 | 0x8080800x8080800x808080&H8080800x808080 |
transparenttransparenttransparenttransparenttransparent | ◻ | -1 | n/a | n/a |
A colour is specified as an IntintintIntegerint value using one of these methods:
- the limited colour names defined as library constants as in the above table.
- an integer in the decimal range 0 (
blackblackblackblackblack) to 224-1 (whitewhitewhitewhitewhite).
- a six digit hexadecimal value in the range
0x0000000x0000000x000000&H0000000x000000 – 0xffffff0xffffff0xffffff&Hffffff0xffffff
using the same 'RGB' format as used in Html style, for example 0xff00000xff00000xff0000&Hff00000xff0000 for red.
transparenttransparenttransparenttransparenttransparent is used only for filling vector graphics shapes.
Elan Library Reference go to the top