Functional-programming-recursion

提供:Dev Guides
移動先:案内検索

関数型プログラミング-再帰

自分自身を呼び出す関数は再帰関数と呼ばれ、この手法は再帰と呼ばれます。 再帰命令は、別の命令がそれを妨げるまで継続します。

C ++の再帰

次の例は、オブジェクト指向プログラミング言語であるC ++での再帰の動作を示しています-

#include <stdio.h>
long int fact(int n);

int main() {
   int n;
   printf("Enter a positive integer: ");
   scanf("%d", &n);
   printf("Factorial of %d = %ld", n, fact(n));
   return 0;
}
long int fact(int n) {
   if (n >= 1)
      return n*fact(n-1);
   else
      return 1;
}

次の出力が生成されます

Enter a positive integer: 5
Factorial of 5 = 120

Pythonの再帰

次の例は、関数型プログラミング言語であるPythonで再帰がどのように機能するかを示しています-

def fact(n):
   if n == 1:
      return n
   else:
      return n* fact (n-1)

# accepts input from user
num = int(input("Enter a number: "))
# check whether number is positive or not

if num > 0:
   print("Sorry, factorial does not exist for negative numbers")
else:
   print("The factorial of " + str(num) +  " is " + str(fact(num)))

それは次の出力を生成します-

Enter a number: 6
The factorial of 6 is 720