Default values

Assigning a default value allows to omit an argument at the function call.
The complete syntax for the heading is:

type [,type]* name(type name [= expression] [, type name [= expression]]* )

This means for:
- the return(s) type(s)
- the identifier
- the argument list
- for each arguement in the list:
- the type
- the identifier
- optionally the = symbol followed by an expression to assign, the default value.

Example of function the argument of which has a default value.
Then, call of the function with either one or two parameters.
int increment(int x, int y = 1)
  x + y
return x

print increment(10, 5)
print increment(10)
Displays: > 15
> 11

When the function is called with a single one parameter, the default value 1 is used to replace the missing parameter.

If the interface of a function has several arguments with a default value, you can't omit one in the call without omitting all following ones. The arguments can't be not recognized by their type.

Using a list

If what you want if to write a function with different numbers and types of parameters at call, you must use an array or a dict instead.

Example of function with a list for argument

The calling of the function passes a list as parameter and the body of the function gets the argument from the list.
text size, name, town

void
param(dict parlist)
  size = parlist["size"]
  name = parlist["name"]
  town = parlist["town"]
return

dict d = dict("170", "someone", "Nice")
param(d)
print size, name, town
Displays: > 170 someone Nice


In this example, the variables: "size", name, "town" are global, and they are assigned from the content of the dictionary passes as parameter;

The function may be called with an dict filled with less than two elements, this should be equivalent to use default value.
One should use in fact, conditonal assigments, thanks to the condional equal symbol:
:=
x := y

x is assigned the value of y only if y is not nil or is x has not yet been assigned.

In the same function, the = symbol is replaced by :=
Thus missing elements in the dict are ignored.
text size, name, town

void
param(dict parlist)
  size := parlist["size"]
  name := parlist["name"]
  town := parlist["town"]
return

dict d = dict("170", "someone")
param(d)
print size, name, town
Displays: > 170 someone


 Exercises

 

1) A function displays a text and a value:
    void name(text x, int y)
       print x, y
   return

The x argument must have for default value, the string "value=".
Rewrite the function.

Answer