我正在使用Haskell实现一个线性代数示例。但是,我在声明magnitude函数时遇到了问题。
我的执行情况如下:
magnitude :: (Foldable t, Functor t, Floating a) => t a -> a
magnitude = sqrt $ Data.Foldable.foldr1 (+) $ fmap (^2)其思想是magnitude将接受Vec2D、Vec3D或Vec4D,并返回其组件的平方和的平方根。
三种向量类型中的每一种都实现了Functor和Foldable。例如,
newtype Vec2D = Vec2D (a, a) deriving (Eq, Show)
instance Functor Vec2D where
fmap f (Vec2D (x, y)) = Vec2D (f x, f y)
instance Foldable Vec2D where
foldr f b (Vec2D (x, y)) = f x $ f y b然而,我收到了许多错误:
LinearAlgebra.hs:9:13:
Could not deduce (Floating (t a -> a)) arising from a use of `sqrt'
from the context (Foldable t, Functor t, Floating a)
bound by the type signature for
magnitude :: (Foldable t, Functor t, Floating a) => t a -> a
at LinearAlgebra.hs:8:14-60
Possible fix: add an instance declaration for (Floating (t a -> a))
In the expression: sqrt
In the expression: sqrt $ Data.Foldable.foldr1 (+) $ fmap (^ 2)
In an equation for `magnitude':
magnitude = sqrt $ Data.Foldable.foldr1 (+) $ fmap (^ 2)
LinearAlgebra.hs:9:20:
Could not deduce (Foldable ((->) (t a -> a)))
arising from a use of `Data.Foldable.foldr1'
from the context (Foldable t, Functor t, Floating a)
bound by the type signature for
magnitude :: (Foldable t, Functor t, Floating a) => t a -> a
at LinearAlgebra.hs:8:14-60
Possible fix:
add an instance declaration for (Foldable ((->) (t a -> a)))
In the expression: Data.Foldable.foldr1 (+)
In the second argument of `($)', namely
`Data.Foldable.foldr1 (+) $ fmap (^ 2)'
In the expression: sqrt $ Data.Foldable.foldr1 (+) $ fmap (^ 2)
LinearAlgebra.hs:9:41:
Could not deduce (Num (t a -> a)) arising from a use of `+'
from the context (Foldable t, Functor t, Floating a)
bound by the type signature for
magnitude :: (Foldable t, Functor t, Floating a) => t a -> a
at LinearAlgebra.hs:8:14-60
Possible fix: add an instance declaration for (Num (t a -> a))
In the first argument of `Data.Foldable.foldr1', namely `(+)'
In the expression: Data.Foldable.foldr1 (+)
In the second argument of `($)', namely
`Data.Foldable.foldr1 (+) $ fmap (^ 2)'
Failed, modules loaded: none.我对Functor或Foldable还不完全满意--我认为这是错误的间接原因。
有人能向我解释一下错误信息指向什么吗?
发布于 2014-05-17 22:35:15
您应该使用(.)而不是($)将您的函数组合成一个管道。发生此错误的原因是,例如,Data.Foldable.foldr1 (+)希望应用于像[a]这样的Foldable类型,但实际上是将它直接应用于作为函数的fmap (^2)。
magnitude :: (Foldable t, Functor t, Floating a) => t a -> a
magnitude = sqrt . Data.Foldable.foldr1 (+) . fmap (^2)或
magnitude :: (Foldable t, Functor t, Floating a) => t a -> a
magnitude ta = sqrt $ Data.Foldable.foldr1 (+) $ fmap (^2) $ ta两者都会做得更好。
https://stackoverflow.com/questions/23716694
复制相似问题