在 C 编程中尝试函数式风格时,我尝试将以下 Haskell 代码转换为 C。
f (0, 0, 0, 1) = 0
f (0, 0, 1, 0) = f (0, 0, 0, 1) + 1
f (0, 1, 0, 0) = f (0, 0, 1, 1) + 1
f (1, 0, 0, 0) = f (0, 1, 1, 1) + 1
f (a, b, c, d) = (p + q + r + s) / (a + b + c + d)
where
p
| a > 0 = a * f (a - 1, b + 1, c + 1, d + 1)
| otherwise = 0
q
| b > 0 = b * f (a, b - 1, c + 1, d + 1)
| otherwise = 0
r
| c > 0 = c * f (a, b, c - 1, d + 1)
| otherwise = 0
s
| d > 0 = d * f (a, b, c, d - 1)
| otherwise = 0
main = print (f (1, 1, 1, 1))
至
#include <stdio.h>
#include <stdlib.h>
#define int const int
#define double const double
double f(int a, int b, int c, int d)
{
if (a == 0 && b == 0 && c == 0 && d == 1)
{
return 0.0;
}
else if (a == 0 && b == 0 && c == 1 && d == 0)
{
return f(0, 0, 0, 1) + 1.0;
}
else if (a == 0 && b == 1 && c == 0 && d == 0)
{
return f(0, 0, 1, 1) + 1.0;
}
else if (a == 1 && b == 0 && c == 0 && d == 0)
{
return f(0, 1, 1, 1) + 1.0;
}
else
{
int p = a > 0 ? a * f(a - 1, b + 1, c + 1, d + 1) : 0;
int q = b > 0 ? b * f(a, b - 1, c + 1, d + 1) : 0;
int r = c > 0 ? c * f(a, b, c - 1, d + 1) : 0;
int s = d > 0 ? d * f(a, b, c, d - 1) : 0;
return (double)(p + q + r + s) / (double)(a + b + c + d);
}
}
int main(void)
{
printf("%f\n", f(1, 1, 1, 1));
return EXIT_SUCCESS;
}
我期望完全相同的行为,但 C 程序总是输出 0.0。它们都输出 0.5 ,f(0, 0, 1, 1)
但是每当数字变大时,C 版本就根本不起作用。出了什么问题?