大学四年来,接触过面向过程的C语言、面向对象的C#,唯独函数式编程没怎么接触过,所以选择了Haskell来学习。
就斐波那契数列的例子来说,用C++的写法是这样的:
// C++ 递归写法
unsigned fib(unsigned n) {
return (n > 1) ? fib(n - 1) + fib(n - 2) : 1;
}
但是顾及效率,通常将递归改写成循环:
// C++ 循环写法
unsigned fib(unsigned n) {
unsigned num = 1;
for (unsigned i = 2, x = 1, y = 1; i <= n; ++i) {
num = x + y;
x = y;
y = num;
}
return num;
}
而对于Haskell,使用哨兵表达式:
-- Haskell 哨兵表达式
fib :: Integer -> Integer
fib n
| n > 1 = fib (n - 1) + fib (n - 2)
| otherwise = 1
使用模式匹配的话:
-- Haskell 模式匹配
fib :: Integer -> Integer
fib 0 = 1
fib 1 = 1
fib n = fib (n - 1) + fib (n - 2)
这个和C++模板特化有点相似:
// C++ 模板元编程
template<int N>
struct Fib {
enum { Result = Fib<N - 1>::Result + Fib<N - 2>::Result };
};
template<>
struct Fib<0> {
enum { Result = 1 };
};
template<>
struct Fib<1> {
enum { Result = 1 };
};
出于效率考虑,我们可以把函数改写为尾递归的形式:
-- Haskell 尾递归
fib :: Integer -> Integer
fib index = fibNum $ fibTuper (0, 1, index)
where fibTuper (x, y, 0) = (x, y, 0)
fibTuper (x, y, n) = fibTuper (y, x + y, n - 1)
fibNum (x, _, _) = x
通过这个例子,可以稍微看出Haskell的一些特点,例如说语法更为精练、表达更为形式化。其中哨兵表达式能简化函数里的if / else结构;而模式匹配类似C++的模板特化,能够处理特殊情况。这样的特性能简化函数体,减少代码量。
总的来说,Haskell还是挺有趣的。