對於Haskell,我很新,在編譯Frag時遇到了這個bug。無法推斷(Eq a),將Eq添加到類型
src/AFRPVectorSpace.hs:51:25:
Could not deduce (Eq a) arising from a use of `/='
from the context (VectorSpace v a)
bound by the class declaration for `VectorSpace'
at src/AFRPVectorSpace.hs:(32,1)-(53,23)
Possible fix:
add (Eq a) to the context of
the class declaration for `VectorSpace'
In the expression: nv /= 0
In the expression:
if nv /= 0 then v ^/ nv else error "normalize: zero vector"
In an equation for `normalize':
normalize v
= if nv /= 0 then v ^/ nv else error "normalize: zero vector"
where
nv = norm v
培訓相關代碼:
class Floating a => VectorSpace v a | v -> a where
zeroVector :: v
(*^) :: a -> v -> v
(^/) :: v -> a -> v
negateVector :: v -> v
(^+^) :: v -> v -> v
(^-^) :: v -> v -> v
dot :: v -> v -> a
norm :: v -> a
normalize :: v -> v
v ^/ a = (1/a) *^ v
negateVector v = (-1) *^ v
v1 ^-^ _ = v1 ^+^ v1 -- (negateVector v2)
norm v = sqrt (v `dot` v)
normalize v = if nv /= 0 then v ^/ nv else error "normalize: zero vector"
where
nv = norm v
我的第一個猜測是,我需要添加一個Deriving Eq
什麼之類的,但我不知道究竟我需要做的。
我要說,你真的不想要一個'Eq'約束對於浮動類型,通常有點麻煩。我寧願添加'class(Num f)=> TestZero f其中{isZero :: f-> Bool}',然後'instance(Eq f,Num f)=> instance TestZero f where {isZero =(== 0)}'。 – leftaroundabout 2013-03-19 10:49:37
沒有必要將'0'轉換爲矢量類型'v'。然而,如果'nv/= 0 then'改爲'if vv/= 0 then'就應該這樣做,因爲'a'是一個數字類型。 – luqui 2013-03-20 13:22:58