A short tutorial - Part 3: FunctionsFebruary 03. 2012
FunctionsFunctions are a basic notion of almost every programming language. In Wirbel functions support both polymorphic programming and overloading. They are defined like in Python: def average(a, b): return (a + b) / 2 The return type of the function depends on the types of the argument. Let's assume you call average with two floats: print(average(1.0, 100.0)) # --> 50.5 The return type will also be a float. If you call average with two integer arguments then it will return an integer. That is because the operators + and / return integer if both arguments are integer (just like in C): print(average(1, 100)) # --> 50 Some functions do not have a return statement at all. They have no return type, since they do not return anything. In their C++ representation their return type is void, but it is not possible to store a void value in a variable or use it in an expression: ERROR: variable cannot store void value
def hello(x):
print("Hello " + x)
a = hello("Mathias") # leads to compile error
Conflicting return typesAt compile time Wirbel wants to determine the type of each expression. The type of the expression average(1, 100) is the return type of average when called with two integers. You have to make sure that all return statements return some value of the same type. You cannot write a function a(x) that - when called with an integer argument - in some cases returns an integer and in other cases a float. But it is allowed for a to return an integer when called with an integer argument, and a float when called with a float argument, as our first example has shown. If execution reaches the end of a function without a return statement and the function has at least one return statement somewhere else, then it will automatically return the neutral value of the functions return type. The neutral value of integer is 0.
def hirn(x):
if x != 0:
return 100 / x
So a call of hirn(0) will return 0. Note that Python implements a different behaviour in returning None if the end of the function is reached without a return statement. |
| ||||||||||||||||||||||||||||||