Recursion
In computer science recursion is a function, which calls itself in the functio body. The function call is always conditional to ensure that calculation ends.
Šaral as a problem-oriented programming langugage supports writing recursive procedures and functions.
Specifics of a recursive function in Šaral
The function recursion is different than in other programming languages. The specification states that there should be only one vrac
(return) statement always on a last line in the function body.
The showcase of a Fibonacci numbers and a calculation of Greatest Common Divisor will highlight how to resolve the specifics.
1 2 3 4 5 6 7 8 9 |
bar neskutočné numeralio fib(neskutočné numeralio n) meňak neskutočné numeralio r keď n <= 2 potom r = 1 inak meňak neskutočné numeralio n1 = n - 1 meňak neskutočné numeralio n2 = n - 2 r = vrac mi z baru fib(n1) + vrac mi z baru fib(n2) vrac r |
1 2 3 4 5 6 7 8 |
bar neskutočné numeralio gcd(neskutočné numeralio d, neskutočné numeralio b) meňak neskutočné numeralio r keď b == 0 potom r = d inak meňak neskutočné numeralio c = d % b r = vrac mi z baru gcd(b, c) vrac r |
Recursive procedure in Šaral
Writing a recursive procedure is easier because no such strict rules apply as for functions.
1 2 3 4 5 6 7 8 |
bar proc(neskutočné numeralio n) keď n > 1 potom meňak neskutočné numeralio n1 = n - 1 ciskaj n1 paľ do baru proc(n1) inak meňak slovo h = "finish" ciskaj h |
More examples in Šaral repository.
Conclusion
Every recursive function should be possible to be rewritten in iterative way and vice versa.
I suppose that there always exists a way how to write every recursive function in different programming language Šaral way.