# This file is supposed to obey the grammar "prog.grammar.sss".
# I have deliberately left in the two errors I made when I wrote it, so you can
# see what SSS does with them. The output of the command
# java org.sc3d.apt.sss.v3.Validator examples/prog.grammar.sss examples/prog.sss
# is in the file called "examples/prog.err".
# The first error is that "while" at line 26 should be "WHILE" (the parser
# thinks it has found a call to a subroutine called "while"), and the second is
# that "int" at line 37 should not be there (the parser thinks that it is a
# variable name).
IMPORT Console Print AS print
IMPORT String Length AS length
IMPORT String Slice AS slice
EXPORT triangle(10) AS Main
# Works out a binomial coefficient: the number of ways of choosing a set of
# 'choose' items from a set of 'from' items.
DEF binomial(from, choose) {
# Works out the factorial of 'n': the product of all the numbers from '1' to
# 'n'. Note that the factorial of '0' is the empty product, equal to '1'.
DEF factorial(n) {
ans = 1
while (n>0) {
ans = ans * n
n = n - 1
}
RETURN ans
}
RETURN factorial(from) / (factorial(choose) * factorial(from-choose))
}
# Returns a function that prints the first 'numRows' rows of Pascal's triangle.
DEF triangle(int numRows) {
# Returns the rightmost 'n' characters of the string 's'.
DEF right(s, n) { RETURN slice(s, length(s)-n, n) }
# The function we're going to return.
DEF run() {
i = 0
WHILE (i