添加2矩阵Erlang

时间:2017-11-13 18:33:36

标签: matrix erlang addition

我有一个问题 我想在erlang中逐行添加2个矩阵,我正在尝试为Haskell应用代码:

add :: Num a => [[a]] -> [[a]] -> [[a]]
add = zipWith $ zipWith (+)

我做了类似的事情:

add([[]],[[]]) -> []
add = zipWith $ zipWith (+)

但这是一个错误,有了$,我真的很困惑。我怎么能在erlang中做到这一点?

以这种方式工作:

  add([[ 1, 2 ],[ 3 , 4 ]] , [[ 4 , 5 ],[ 6 , 7 ]] ).
  

结果:

[[ 6, 8], [ 10, 12]]

2 个答案:

答案 0 :(得分:3)

这是你的Haskell函数到Erlang的方向转换:

add(Xss, Yss) ->
  lists:zipwith(fun(Xs, Ys) -> lists:zipwith(fun(X, Y) -> X + Y end, Xs, Ys) end, Xss, Yss).

(+)变为fun(X, Y) -> X + Y end,因为Erlang没有$运算符或函数的自动部分应用,我们需要命名所有参数并将它们显式传递给{{ 1}}。

按预期工作:

lists:zipwith

答案 1 :(得分:1)

1> shell:strings(false).            
true
2> AddRow = fun(X, Y) -> lists:zipwith(fun erlang:'+'/2, X, Y) end.
#Fun<erl_eval.12.99386804>
3> Add = fun(X, Y) -> lists:zipwith(AddRow, X, Y) end.             
#Fun<erl_eval.12.99386804>
4> Add([[1,2],[3,4]],[[4,5],[6,7]]).                               
[[5,7],[9,11]]