8.1 Simple function definitions
You can define simple calculations easily. We'll use a classic example:
fun square (x:int) => x * x;
square just multiplies its argument
x by itself.
We can use it now:
write$ stdout, "Input number: "; fflush stdout; val result = readln$ stdin; val cleaned_result = strip result; val v = int cleaned_result; val v2 = square v; println$ "Square of " + str v + " is " + str v2;
Input number: 42 Square of 42 is 1764
funbinder introduces the function
squareaccepts a single argument of type
- The operator
*is used for multiplication.
squarereturns the product of its argument with itself.
- The type of value returned by
squareis deduced by the compiler, that type will be
intbecause multiplying an
- The type
intcan also be used as a function to convert a
stringcontaining only digits to an
- The function
strcan be used to convert an
intto a string.
There is a rule for functions:
A function introduced by a
funbinder is not allowed to have any side effects.
The compiler does not enforce this rule, but it does take advantage of it when optimising your code.