使用类型约束时无法推断错误



我使用Haskell来实现一个线性代数的例子。但是,我在声明magnitude函数时遇到了一个问题。

我的实现如下:

magnitude :: (Foldable t, Functor t, Floating a) => t a -> a
magnitude = sqrt $ Data.Foldable.foldr1 (+) $ fmap (^2)

思想是magnitude将接受Vec2D, Vec3DVec4D,并返回其分量平方和的平方根。

三种vector类型都实现了FunctorFoldable。例如,

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.

我对FunctorFoldable还不是很熟悉,我相信这是导致错误的间接原因。

谁能给我解释一下错误信息是指什么?

您应该将您的函数与(.)而不是($)组合到一个管道中。发生此错误的原因是,例如,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

相关内容

  • 没有找到相关文章

最新更新