Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is my Fibonacci subroutine an example of recursion in Perl?

Tags:

recursion

perl

As we all know that we can send any number of arguments to a subroutine in Perl. Would the following example be a correct demonstration of recursion to display fibonacci series (5 values)?

#!/usr/bin/perl -w

use strict;

sub recursion
{
  if ($_[0] && $_[2])
  {
    print $_[2],"\n";
    if ($_[0] < 5)
    {
       return recursion($_[0] + 1, $_[2], $_[1] + $_[2]);
    }
    else
    {
       return $_[0];
    }
  }
  elsif ($_[0] && !$_[1] && !$_[2])
  {
    print "0\n";
    return recursion($_[0], 0, 1);
  }
}
print "\nFibo Series : \n";
recursion(1);

print "\nEnter to exit";
<>;

I know it is a lame example… but my aim is to know whether this type of implementation would still qualify to be an example for recursion?
Hoping for no brickbats :)

Edit:

depending upon some condition, if the program decides to send only one argument or two or multiple arguments to itself… would that be a valid characteristic?

like image 428
topgun_ivard Avatar asked Feb 27 '23 05:02

topgun_ivard


2 Answers

A function is recursive if it calls itself. Your recursion function calls itself, so it's recursive. codaddict's conditions are necessary for a recursive function to work properly, but a function could still be recursive if they weren't met. (It would just be recursive and buggy.)

like image 101
cjm Avatar answered Mar 08 '23 03:03

cjm


Yes. Its a recursive function. It meets the required conditions of

  • There should be a way to terminate recursion. In your case when $_[0] becomes 5
  • Recursive call should move towards the terminating case. You pass $_[0] + 1 to recursive calls.
like image 29
codaddict Avatar answered Mar 08 '23 02:03

codaddict