In the following example we define a function sign which determines
the sign of a number.
gap> sign:= function(n) > if n < 0 then > return -1; > elif n = 0 then > return 0; > else > return 1; > fi; > end; function ( n ) ... end gap> sign(0); sign(-99); sign(11); 0 -1 1
This example also introduces the if statement which is used to execute
statements depending on a condition. The if statement has the
following syntax.
if condition then
statements
elif condition then
statements
else
statements
fi
There may be several elif parts. The elif part as well as the else
part of the if statement may be omitted. An if statement is no
expression and can therefore not be assigned to a variable. Furthermore
an if statement does not return a value.
Fibonacci numbers are defined recursively by f(1) = f(2) = 1 and
f(n) = f(n-1) + f(n-2) for n ³ 3.
Since functions in GAP may call themselves,
a function fib that computes Fibonacci numbers can be implemented
basically by typing the above equations. (Note however that this is a very
inefficient way to compute f(n).)
gap> fib:= function(n) > if n in [1, 2] then > return 1; > else > return fib(n-1) + fib(n-2); > fi; > end; function ( n ) ... end gap> fib(15); 610
There should be additional tests for the argument n being a positive
integer. This function fib might lead to strange results if called
with other arguments. Try inserting the necessary tests into this example.
[Top] [Previous] [Up] [Next] [Index]
GAP 4 manual