C语言伪代码
矩阵加法在 C 语言中很容易实现,伪代码如下:
mat matadd(mat a, mat b){mat result;for (int i = 0; i < x.rows; ++i){for (int j = 0; j < x.cols; ++j){result[i][j] = a[i][j] + b[i][j]}}
return result;
}
Haskell 递归算法实现
函数式编程没有循环命令,用递归实现循环,上面的两个循环,需要用两个等价的递归函数实现:
matadd :: Num(a)=>[[a]]->[[a]]->[[a]]
matadd [] [] = []
matadd (x:xs) (y:ys) = (rowadd x y):(matadd xs ys)where rowadd :: Num(a)=>[a]->[a]->[a]rowadd [] [] = []rowadd (x:xs) (y:ys) = (x+y):(rowadd xs ys)
利用高阶函数简化算法
上述算法可以借助高阶函数代替rowadd,简化如下:
matadd' :: Num(a)=>[[a]]->[[a]]->[[a]]
matadd' [] [] = []
matadd' (x:xs) (y:ys) = (zipWith (+) x y):(matadd' xs ys)
更进一步,可化简成如下形式:
matadd'' x y = zipWith (zipWith (+)) x y
试验一下,结果如下:
>> matadd'' [[1,2],[3,4]] [[5,6],[7,8]]
[[6,8],[10,12]]
C 语言 6 行代码,Haskell 语言一行搞定,函数式编程优势在这里表现明显。矩阵加法相对简单,矩阵乘法感觉不好对付,留作下一个练习题来处理吧。我想通过矩阵乘法的实现继续探索函数式编程的秘密。