ExpandCollapsePrev Next Index

+ 8.1 Simple function definitions

You can define simple calculations easily. We'll use a classic example:

  fun square (x:int) => x * x;

The function 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


  • The fun binder introduces the function square.
  • square accepts a single argument of type int.
  • The operator * is used for multiplication.
  • square returns the product of its argument with itself.
  • The type of value returned by square is deduced by the compiler, that type will be int because multiplying an int by another int yields an int.
  • The type int can also be used as a function to convert a string containing only digits to an int.
  • The function str can be used to convert an int to a string.

There is a rule for functions:

A function introduced by a fun binder 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.