Library constants
Name | Type | value |
openBrace | String | { |
closeBrace | String | } |
quotes | String | " |
Library Colours
Colour name | Integer decimal | R G B decimal | R G B hexadecimal |
black | 0 | 0 0 0 | 0x000000 |
white | 16777215 | 255 255 255 | 0xffffff |
red | 16711680 | 255 0 0 | 0xff0000 |
green | 32768 | 0 128 0 | 0x008000 |
blue | 255 | 0 0 255 | 0x0000ff |
yellow | 16776960 | 255 255 0 | 0xffff00 |
brown | 10824234 | 165 42 42 | 0xa52a2a |
grey | 8421504 | 128 128 128 | 0x808080 |
Library 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 declaration (variable) or assignment (set), either on their own or within a more complex expression. All standalone library functions require at least one argument to be passed in brackets, corresponding to the parameters defined for that function.
unicode
unicode(code as Int) returns String
converts a Unicode value (expressed in decimal or hexadecimal notation) into a single character string. For example:
function hearts() return string
return unicode(0x2655)
end function
parseAsInt and parseAsFloat
parseAsInt(inp as String) returns (Boolean, Int)
parseAsFloat(inp as String) returns (Boolean, Float)
parseAsInt attempts to parse the input String as an Int and returns a 2-tuple, the first value of which is Boolean, with true indicating whether or not the parse has succeeded, and the second value being the resulting Int. parseAsFloat does the equivalent for floating point.
print parseAsInt("31") _ (true, 31)
print parseAsFloat("31") _ (true, 31)
print parseAsInt("31.2) _ (false, 0)
print parseAsFloat("31.2") _ (true, 31.2)
print parseAsInt("0") _ (true, 0)
print parseAsInt("0") _ (true, 0)
Notes
Any string that parses as an Int will also parse as a Float.
If the parse fails, the second value will become zero, so you should always check the first value to see if the second value is a correct parse or just the default.
You can ‘deconstruct’ the tuple into two variables:
variable outcome, value set to parseAsInt(myString)
One use of these parsing methods is for validating user input, but note that there is an easier way to do this.
floor, ceiling, and round
floor(inp as Float) returns Int
returns the nearest integer value below (or equal to) the argument value. Usage:
print floor(2.5) _ 2
ceiling(inp as Float) returns Int
returns the nearest integer value above (or equal to) the input value. Usage:
print ceiling(2.5) _ 3
round(inp as Float, places as Int) returns Float
Rounds the input number of decimal places specified as the second argument (an Int). Usage:
print round(3.14159, 3) _ 3.142
Maths functions and constants
Function | Argument Type | Input unit | Returns | Output unit |
pi | (none) | | 𝜋 = 3.141592653589793.. | |
abs | Float | | absolute value of the input | |
acos | Float | | arccosine of the input | radians |
asin | Float | | arcsine of the input | radians |
atan | Float | | arctangent of the input | radians |
acosDeg | Float | | arccosine of the input | degrees |
asinDeg | Float | | arcsine of the input | degrees |
atanDeg | Float | | arctangent of the input | degrees |
cos | Float | radians | cosine of the input | |
cosDeg | Float | degrees | cosine of the input | |
exp | Float | | 𝑒𝑥 where 𝑥 is the argument and 𝑒 is Euler's number 2.718281828459045.. the base of natural logarithms | |
logE | Float | | natural logarithm of the input | |
log10 | Float | | base-10 logarithm of the input | |
log2 | Float | | base-2 logarithm of the input | |
sin | Float | radians | sine of the input | |
sinDeg | Float | degrees | sine of the input | |
sqrt | Float | | positive square root of the input | |
tan | Float | radians | tangent of the input | |
tanDeg | Float | degrees | tangent of the input | |
degToRad | Float | degrees | converts input from degrees to radians | radians |
radToDeg | Float | radians | converts input from radians to degrees | degrees |
Examples of some maths functions being tested:

Regular expressions
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 testRegExp is applied to a String using dot syntax and requires a RegExp parameter specified as a literal or as variable. It returns a Boolean. For example:

You can convert a valid string without /../ delimiters to a RegExp using function asRegExp:

Although it is recommended that literal regular expressions are written with the /../ delimiters, the ability to convert a string allows you to input a regular expression into a running program.
Bitwise functions
bitAnd(a as Int, b as Int) returns Int
bitOr(a as Int, b as Int) returns Int
bitXor(a as Int, b as Int) returns Int
bitNot(a as Int) returns Int
bitShiftL(a as Int, places as Int) returns Int
bitShiftR(a as Int, places as Int) returns Int
Examples of the bitwise functions being tested:

The result of bitNot(a), where a is 13, being -14 might be a surprise. But this is because the bitwise functions assume that the arguments are represented as 32-bit signed integers. So 13 is represented as 00000000000000000000000000001101, and applying bitNot gives 11111111111111111111111111110010 which is the value -14 in signed two’s complement format, the left-most bit being the sign (0 positive, 1 negative).
Library procedures
All procedures are accessed via a call statement.
pause
pause
is used to slow down the execution of a program e.g. for a game. The argument provided to pause is in milliseconds, so pause(100) delays execution for one tenth of a second.
clearConsole
clearConsole()
clearKeyBuffer
clearKeyBuffer()
printLine
printLine(arg as String) prints the argument followed by a new line.
The primary purpose of this is so that you may choose to do all printing via methods rather than mixing them in with print statements.
Note that the argument must be provided as a String.
printNoLine
printNoLine(arg as String) does not automatically add a newline at the end,
so you may subsequently print something else on the same line (unless you choose to include a newline \n within the string).
Note that the argument must be provided as a String.
printTab
printTab(tabPosition as Int, arg as String)
helps in the layout of information printed to the console, in particular, when printing columns of data. printTab requires an additional argument specifying the tab position which is number of characters from the left of the display. For example:
Note that the argument must be provided as a String.
+main1
call printTabprocedureName?(0, "No."arguments?)2
call printTabprocedureName?(10, "Square"arguments?)3
call printTabprocedureName?(20, "Cube\n"arguments?)4
+for xvariableName? from 1expression? to 10expression? step 1expression?5
call printTabprocedureName?(0, x.asString()arguments?)6
call printTabprocedureName?(10, "{x^2}"arguments?)7
call printTabprocedureName?(20, "{x^3}\n"arguments?)8
end for
end main
or, to right-align numeric output:
variable tab set to 10
variable i set to 0
for i from 1 to (tab – 1) step 1
variable j set to 10^i
call printTab(tab - digits(j), "{j}\n")
function digits(number as Int) returns Int
return number.asString().length()
end function
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 are used in expressions
However, system methods are not pure functions because:
They may have a dependency on data that is not provided as 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 within a procedure. System methods may not be used inside a function that you have defined, because to do so would mean that your function would not be pure.
System methods are all defined within the Elan standard library. You cannot write a system method yourself.
System methods are commonly associated with Input/Output, but note that:
Input/output may also be performed via procedures
Some system methods do not appear to be concerned with input/output: see the list below
The reason those are system methods is that they have a dependency on variable data that is not passed into them as arguments
clock
clock Returns an integer that increments every millisecond. It is useful for measuring elapsed time by comparing the values returned by two such evaluations of the clock method.
getKey
getKey()
getKeyWithModifier
getKeyWithModifier()
inputString(prompt as string)
inputStringWithLimits(prompt as string, minLength as Int, maxLength as Int)
inputStringFromOptions(prompt as String, options as Array)
inputInt(prompt as string)
inputIntBetween(prompt as string, min as Int, max as Int)
inputFloat(prompt as string)
inputFloatBetween(prompt as string, min as Float, max as Float)
openFileForReading
openFileForReading: see Reading textual data from a file
random
random and randomInt: see Generating random numbers
waitForAnyKey
waitForAnyKey()
Library Types and their dot methods
TextFileReader
The TextFileReader class is used to read textual data from a file.
An instance is created by the standalone system method openFileForReading, on
which the dot-methods the following methods may be invoked:
readLine
readWholeFile
endOfFile
close
These methods may be used to read a whole file in one go:
let filename? be openFileForReading()expression?2
let textname? be file.readWholeFile()expression?3
call file.closeprocedureName?(arguments?)4
print textexpression?5
or to read a file line by line:
+main1
let filename? be openFileForReading()expression?2
variable linesname? set to empty Array<of String>expression?3
+while not file.endOfFile()condition?4
let linename? be file.readLine()expression?5
call lines.appendprocedureName?(linearguments?)6
end while
call file.closeprocedureName?(arguments?)7
Notes
openFileForReading will present the user with a dialog to select the file.
readWholeFile returns a String containing every character in the file, without any trimming. It automatically closes the file after the read.
readLine 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 String. If this behaviour is not desired, you can use readWholeFile, which does no trimming, and then parse the resulting String into separate lines.
Calling file.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 readWholeFile() because that method automatically closes the file.
Calling any method on a file that is already closed will result in a runtime error.
TextFileWriter
The TextFileWriter class is used to write textual data to a file.
An instance is created by the standalone system method createFileForWriting, on
which the dot-methods the following methods may be invoked:
writeLine
writeWholeFile
saveAndClose
These methods may be used to write a whole file in one go:
let fname? be createFileForWriting("myFile.txt")expression?2
call f.writeWholeFileprocedureName?("this is\nmyText"arguments?)3
or to write a file line by line:
+main1
let filename? be createFileForWriting("squares.txt")expression?2
+for ivariableName? from 1expression? to 100expression? step 1expression?3
call file.writeLineprocedureName?("{i} {i*i}"arguments?)4
end for
call file.saveAndCloseprocedureName?(arguments?)5
end main
Notes
writeLine adds the string it is passed onto the end of any data previously written, with a newline character (\n) automatically appended.
When execution reaches saveAndClose() 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 createFileForWriting.
writeWholeFile 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 saveAndClose had been called.
Calling any method on a file that has already been closed (by calling either saveAndClose or by writeWholeFile) will result in a runtime error.
If the user were to hit Cancel on the save dialog, then the program will exit with an error. If you want to guard against this possibility (if, for example, it might mean the loss of important data) then you should perform the save and close within a try..catch like this:
+try 3
call file.saveAndCloseprocedureName?(arguments?)4
+catch exception in evariableName?5
print "File save cancelled"expression?6
end try
or you could make the code offer the user options: to save again, or to continue without saving.
Block graphics
Block graphics provides a simple way to create low resolution graphics, ideal for simple but engaging games for example. The graphics are displayed on a grid that is 40 blocks wide by 30 blocks high.
Each block may be rendered as a solid colour. Each block may alternatively hold a symbol: either one of the standard text characters or any Unicode symbol and, in each case, with specified foreground and background colours. For specifying colours, see Colour.
An example of block graphics to produce a rapidly changing pattern of coloured blocks:
+main1
variable grname? set to new BlockGraphics()expression?2
+while truecondition?3
let xname? be randomInt(0, 39)expression?4
let yname? be randomInt(0, 29)expression?5
let colourname? be randomInt(0, 2^24 - 1)expression?6
set grvariableName? to gr.withBlock(x, y, colour)expression?7
call gr.displayprocedureName?(arguments?)8
end while
end main
Notes
Making changes to the instance of BlockGraphics (gr above) – for example by calling withBlock above – does not of itself result in anything appearing in the Graphics screen. The Graphics screen changes only when the display() procedure is called. This is so that you can make many changes to the graphics and then have them appear all at once (when display is called). It is even possible to create and modify, multiple instances of BlockGraphics, and switch instantly between them by calling display on different instances.
The coordinates must be in the range 0-39 for a column, and 0-29 for a row. Using values outside this range will result in a runtime error.
Colour is always specified as an integer: see Colour.
The withBlock method does not change the instance of BlockGraphics on which it is called, but returns a new instance of BlockGraphics based on the original with the change specified. This new instance may, however, be re-assigned to the same variable – as is the case in the code above.
In addition to withBlock, there are these three function methods for updating the graphics:
withText(x as Int, y as Int, text as String, foreground as Int, background as Int) returns BlockGraphics
If the text argument is more than one character long, the characters will be placed in successive blocks, wrapping onto the next line if necessary. (If the string is too long to fit, from the starting coordinates specified, you will get a runtime error). Use only ASCII characters with values in the range 32 space) through 254 lower-case thorn).
withUnicode(x as Int, y as Int, unicode as Int, foreground as Int, background as Int) returns BlockGraphics
is used to specify a single symbol or character using its Unicode codepoint value.
withBackground(backgroundColour as Int) returns BlockGraphics
will paint the background colour for the whole grid, leaving any existing characters (and their foreground colours) unchanged.
There are also function methods on a BlockGraphics instance for reading the existing character and colours of a specified block:
getChar(x as Int, y as Int) returns String
getForeground(x as Int, y as Int) returns Int
getBackground x as Int, y as Int) returns Int
Turtle graphics
Example code:
main
let t be new Turtle()
call t.show()
for i from 1 to 4 step 1
call t.turn(90)
call t.move(100)
call t.pause(500)
end for
end main
Output:

Notes
move and turn are the two most commonly-used methods. To move backwards, specify a negative value. The value passed into turn is interpreted as degrees: a positive value turns clockwise; a negative value anti-clockwise. Both methods take a numeric value, which may be an Int or a Float.
Scaling: the argument provided to the move procedure is specified in ‘turtle-units’. The Graphics pane on the screen (i.e. the ‘paper’ on which the Turtle draws) is 100 turtle units wide by 75 turtle units high. If the turtle is moved outside these boundaries it will not cause an error, but the location of the turtle and any lines outside the boundaries will not be visible.
show causes the turtle to be displayed (the small green circle with a black radius showing the direction it is pointing); hide does the opposite. You can move and turn the turtle, causing lines to be drawn, whether or not the turtle is shown.
To move the turtle without drawing a line call penUp, then penDown when you are ready to draw lines again.
penColour takes an integer argument specifying the colour. For specifying colours, see Colour.
penWidth specifies the width of the line drawn by the turtle which must be an integer. The default is the minimum value of 1.
You can specify the start position of the turtle in x,y coordinates (0,0 being the top-left of the Graphics pane) with placeAt, which may also be used to reposition the turtle (without drawing a connecting line) during the program run. You may specify the turtle’s absolute heading with turnTo, where 0 would cause the turtle to face up the screen.
The current location and heading of the turtle may be read using the x, y, and heading properties.
There is no difference in effect between call t.pause(500) and the standalone call pause(500): the former option is provided as a convenience, because most instructions in a Turtle program take the form call t.something. Both versions take an integer argument, being the length of the pause in milliseconds.
Apart from the penColour and pause methods, both of which require an integer value, all other procedure methods on the Turtle can take integer or floating-point values.
Here is a more sophisticated example, using a procedure and recursion, that produces a fractal snowflake:
main
variable t set to new Turtle()
call t.placeAt(10, 60)
call t.turn(90)
call t.show()
for i from 1 to 3 step 1
call drawSide(160, t)
call t.turn(120)
end for
end main
procedure drawSide(length as Float, out t as Turtle)
if (length > 3) then
let third be length/3
call drawSide(third, t)
call t.turn(-60)
call drawSide(third, t)
call t.turn(120)
call drawSide(third, t)
call t.turn(-60)
call drawSide(third, t)
else
call t.move(length)
end if
end procedure

Vector graphics
Example:
main
variable vg set to new VectorGraphics()
let circ be new CircleVG() with cx to 35, cy to 35, r to 5, stroke to red, strokeWidth to 2, fill to green
set vg to vg.add(circ)
call vg.display()
end main
Output:

Notes
Elan vector graphics are displayed using SVG (Scalable Vector Graphics) that are a part of the Html specification. The names of the shapes broadly correspond to the names of SVG tags: CircleVG for <circle../>, LineVG for <line../>, and RectangleVG for <rect../>. The properties of the Elan VG shapes match the names of the attributes used in the SVG tags, except that the stroke-width attribute is changed to strokeWidth to make it a valid Identifier.
The ‘canvas’ on which vector graphics are drawn (the Graphics pane in the user interface) is 100 units wide, by 75 units high .All numeric values specified for attributes of vector graphic shapes may be integer or floating point.
All Elan ..VG shapes have default values for all attributes, and so will show up even if no attributes have been specified. You can specify as many of the attributes as you wish when creating the shape using the new .. with syntax, as shown in the example above.
As with Block graphics the screen is not updated until the display method is called, allowing you to make multiple changes before updating the screen. Similarly, the method to add a shape returns a new instance of the VectorGraphics which must be assigned either to an existing variable, or to a new let.
As with the way that SVG works within Html, the shapes are drawn in the order in which they are added into the VectorGraphics instance, with later shapes positioned over earlier shapes.
The colour (for stroke and fill properties) may be specified as described at Colour. The fill colour only may also be specified as ‘transparent’ by giving it a negative value; we suggest using fill to -1
VectorGraphics also has methods removeLast (no parameters), remove (which takes a shape as a parameter, and replace which takes an existing shape and a new shape as parameters. The new shape may be a modified version of an existing shape (created using copy .. with), thereby enabling animation. The following simple example creates a circle that changes between red and green every second:
BaseVG is the abstract superclass of all .VG shapes.
You would only use if if you wanted to define a method that could work on any shape (using common members defined on BaseVG)
or that could work with a List holding different types of shape.
main
variable vg set to new VectorGraphics()
let greenCirc be new CircleVG() with cx to 50, cy to 37, r to 30, fill to green
let redCirc be copy greenCirc with fill to red
set vg to vg.add(greenCirc)
while true
call vg.display()
call pause(1000)
set vg to vg.replace(greenCirc, redCirc)
call vg.display()
call pause(1000)
set vg to vg.replace(redCirc, greenCirc)
end while
end main
Stack and queue
Stack and Queue are similar data structures except that Stack is ‘LIFO’ (last in, first out), while Queue is FIFO (first in, first out). The names of the methods for adding/removing are different, but there are also common methods, summarised here.
Both a Stack and a Queue are defined with the Type of the items that they can contain, similarly to how Array and List have a specified item Type, though with different syntax. The Type is specified in the form shown below e.g. Stack<of String>, Queue<of Int>, Stack<of (Float, Float)>, Queue<of Square>.
Both Stack and Queue are dynamically extensible, like Array and List. There is no need (or means to) specify a size limit as they will continue to expand until, eventually, the computer’s memory limit is reached.
This same syntax is used to specify the Type if you want to pass a Stack into a function, or specify it as the return Type.
Stack and Queue have some methods in common: length(), and peek() which allows you to read the next item that would be removed, without actually removing it.
The names of the methods for adding or removing an item are different for Stack and Queue, as summarised in this table:
| Stack | Queue |
Create a new instance | let s be new Stack<of Int>() | let q be new Queue<of Int>() |
Add an item (must be of correct Type) | call s.push(item) | call q.enqueue(item) |
Remove the next item | variable item set to s.pop() | variable item set to q.dequeue() |
View the next item to be removed without removing it | variable item set to s.peek() | variable item set to q.peek() |
Read the current length | s.length() | q.length() |
Example use of a Stack:
main
let sk be new Stack<of String>()
print sk.length()
call sk.push("apple")
call sk.push("pear")
print sk.length()
print sk.peek()
variable fruit set to sk.pop()
print fruit
set fruit to sk.pop()
print fruit
print sk.length()
end main
Example use of a Queue:
main
let qu be new Queue<of String>()
print qu.length()
call qu.enqueue("apple")
call qu.enqueue("pear")
print qu.length()
print qu.peek()
variable fruit set to qu.dequeue()
print fruit
set fruit to qu.dequeue()
print fruit
print qu.length()
end main
Set
A Set is a standard data structure that works somewhat like a List with the important difference that in a Set a given element may appear only once. If an item being added to a Set is identical to an existing item in the Set then the Set remains the same length as before.
This enables a Set to work like a mathematical set so that it is possible to perform standard set operations such as union or intersection. For the same reason, a Set is an immutable data structure: there are no methods modify the set on which they are called, but several of them (including add, remove) return a new Set that is based on the original Set or Sets, with specified differences.
Example of use:
main
variable st set to new Set<of Int>()
set st to st.addFromList({3, 5, 7})
print st.length()
set st to st.add(7)
print st.length()
set st to st.remove(3)
print st.length()
set st to st.remove(3)
print st.length()
print st
end main
Notes
When creating a Set, the Type of the elements must be specified in the form
Set<of String>. This applies both when creating a new, empty set and when defining the Type of a parameter to be a Set.
You can add elements: individually with add, or multiple elements with addFromList and addFromArray.
You can create a new Set from an existing Array or List by calling .asSet() on it.
Available dot methods on a Set, and the Type that each returns:
length()
contains(item)
add(item)
addFromList(list)
addFromArray(array)
remove(item)
union(anotherSet)
difference(anotherSet)
intersection(anotherSet)
isDisjointFrom(anotherSet)
isSubsetOf(anotherSet)
isSupersetOf(anotherSet)
asArray(anotherSet)
asList(anotherSet)
asString()
max and min
Both these functions may be applied to an List<of Float> and return the maximum or minimum value found therein.
variable a set to {33, 4, 0,99, 82, 55}
print "Max: {a.max()} Min: {a.min()}"
Higher order functions (HoFs)
These dot methods are called on any Array, List or String. As ‘higher order functions’ they take either a lambda or a function reference as one of their arguments: see Passing a function as a reference.
Important: Several of these methods return a List but this may be converted to an array using .asArray() at the end of the expression.
These are not yet fully documented but, for readers familiar with HoFs from another programming language, some examples are shown below.
filter
Usage:
let matches be rules.filter(lambda r as Rule =>
(r.currentState is currentState) and (r.currentSymbol is tape[headPosition]))
map
Usage:
let next be cellRange.map(lambda n as Int => nextCellValue(cells, n))
reduce
Usage:
let d2 be possibleAnswers.reduce(d,
lambda dd as Dictionary<of String, Int>, possAnswer as String =>
incrementCount(dd, possAnswer, attempt))
maxBy and minBy
Alternative implementations of max and min:
variable a set to {33, 4, 0,99, 82, 55}
print a.maxBy(lambda x as Int => x mod 10)
sortBy
sortBy takes a lambda that takes two arguments (of the same Type as that of the List being sorted) and compares them, returning an integer with one of the values -1, 0, or +1, to indicate whether the first argument should be placed respectively before, adjacent to or after the second argument in the sorted result, where ‘adjacent to’ means it does not matter whether before or after):
variable source set to {11, 3, 7, 37, 17, 2, 19, 5, 23, 27, 31, 13}
print source.sortBy(lambda x as Int, y as Int => if x > y then 1 else -1).asList()
The following are not HoFs, but are included here because they are most likely to be used with one of the HoFs listed above.
range
range(first as Int, last as Int) as List<of Int>
returns a List containing all the integer values between the two argument values.
Dot methods that work on many different Types
.asString()
.length()
.head() returns the first item in an Array or a List