2011
08.03

Simple functions

Simple functions in Kronos are homomorphic. It means that they have a single form regardless of the context. This is likely what you would intuitively expect. Let’s revisit the simple function we defined in part 1.

Take-Square(x)
{
	Take-Square = x * x
}

The definition has four mandatory parts:

  1. Symbol, ‘Take-Square’
  2. Argument binding, ‘(x)’
  3. Scope, contents of {}
  4. A definition of the function symbol ‘Take-Square = …’

These four elements must be present in all function definitions.

The function definition can be placed anywhere in the source file. In case of simple functions, the placement has no effect.

At the moment, function definitions can not be nested. This means that functions can’t be defined within another function definition. This restriction may be lifted at some point, though – nested functions combined with closures can be useful. But I digress.

Using functions

You may use a function by supplying a symbol and an argument bundle together. There must be no whitespace between the symbol and argument. Like so:

/* Right, a function call */
nine? = Take-Square(3)
/* Wrong, syntax error! */
nine? = Take-Square (3)

This binds ‘nine?’ to the value of the function ‘Take-Square’ with the argument 3.

First class functions

Functions can also appear without arguments. Take a look;

PS C:\Users\Vesa\Kronos.Preview1> .\k2cli.exe .\part3-myfunc.k
K2CLI 0.1
(c) 2011 Vesa Norilo

EXPR>Take-Square(3)
Take-Square(3) => 9
EXPR>Take-Square
Take-Square => ':Mul((Mul) pair(arg arg))
EXPR>

What emerges may seem like gibberish but is actually the abstract syntax tree associated with the ‘Take-Square’ function. The result of this evaluation is not any particular square, but rather a program to take a square.

This means that functions are first class. Basically, functions can appear as parts of expressions, passed as arguments and returned as values. Such a function can be explicitly called by using ‘Eval’ which takes a function definition and an argument.

EXPR>Eval(Take-Square 9)
Eval(Take-Square 9) => 81

This pattern will start to make sense once you study higher order functions.

In part 4, we will examine polymorphic functions.

No Comment.

Add Your Comment


× eight = 64