【发布时间】:2018-10-02 20:14:14
【问题描述】:
我正在尝试覆盖 + 符号以学习如何定义我自己的类型。我对 Haskell 很陌生,我似乎无法克服这个错误。
这是我的简单新类型:
newtype Matrix x = Matrix x
(+):: (Num a, Num b, Num c) => Matrix [[a]] -> Matrix [[b]] -> Matrix [[c]]
x + y = Matrix zipWith (\ a b -> zipWith (+) a b) x y
当我尝试将它加载到 ghci 中时,我得到了错误
linear_algebra.hs:9:42:
Ambiguous occurrence ‘+’
It could refer to either ‘Main.+’, defined at linear_algebra.hs:9:3
or ‘Prelude.+’,
imported from ‘Prelude’ at linear_algebra.hs:1:1
(and originally defined in ‘GHC.Num’)
Failed, modules loaded: none.
用
替换我的最后一行代码x + y = Matrix zipWith (\ a b -> zipWith (Prelude.+) a b) x y
给我错误
Couldn't match expected type ‘([Integer] -> [Integer] -> [Integer])
-> Matrix [[a]] -> Matrix [[b]] -> Matrix [[c]]’
with actual type ‘Matrix
((a0 -> b0 -> c0) -> [a0] -> [b0] -> [c0])’
Relevant bindings include
y :: Matrix [[b]] (bound at linear_algebra.hs:9:5)
x :: Matrix [[a]] (bound at linear_algebra.hs:9:1)
(+) :: Matrix [[a]] -> Matrix [[b]] -> Matrix [[c]]
(bound at linear_algebra.hs:9:1)
The function ‘Matrix’ is applied to four arguments,
but its type ‘((a0 -> b0 -> c0) -> [a0] -> [b0] -> [c0])
-> Matrix ((a0 -> b0 -> c0) -> [a0] -> [b0] -> [c0])’
has only one
In the expression:
Matrix zipWith (\ a b -> zipWith (Prelude.+) a b) x y
In an equation for ‘+’:
x + y = Matrix zipWith (\ a b -> zipWith (Prelude.+) a b) x y
Failed, modules loaded: none.
你能帮我理解错误是什么吗?我真的很感激。谢谢!
【问题讨论】:
-
不能在 Haskell 中覆盖,只能实现一个类型类,比如
Num类型类:learnyouahaskell.com/… -
坦率地说,让
Matrix成为Num的实例是没有意义的。 (你可以,如果你真的想......但是矩阵的符号是什么?fromInteger 3应该计算成什么矩阵?) -
请务必仔细阅读错误消息“...函数‘Matrix’应用于四个参数,但它的类型只有一个,在表达式
Matrix zipWith (\ a b -> zipWith (Prelude.+) a b) x y...中”。你缺少括号
标签: function haskell matrix types constructor