我一直习惯于命令式编程,这是通常告诉计算机逐步执行过程以获得最终结果的方式。另一方面,声明式编程只传递输入并期望输出,而不陈述完成任务的具体过程。我感到困惑的是函数式编程。我知道函数式编程是一种将计算视为数学函数求值的编程范式,避免状态和可变数据,并不是一种声明式语言。然而,我仍然无法理解它的工作原理。
让我们以斐波那契数列的执行为例。
命令式编程:
#include<stdio.h>
#include<conio.h>
main()
{
int n,i,c,a=0,b=1;
printf("Enter Fibonacci series of nth term : ");
scanf("%d",&n);
printf("%d %d ",a,b);
for(i=0;i<=(n-3);i++)
{
c=a+b;
a=b;
b=c;
}
printf("%d ",c);
getch();
}
声明式编程:
Give the nth number and it will return the value of the nth number
函数式编程如何工作?另外,如果我的定义有误,请纠正我。请随意评论。