Haskell:无法推断使用“cos”引起的(浮动t)

时间:2016-08-12 12:13:21

标签: haskell

我正在学习Haskell,我试图根据我在Internet上找到的资源实现一些量子门。 目前,我成功实现了Z门,X门,H门,但我在实现旋转门时遇到了问题。

U = [[cos t  -sin t] 
     [sin t  cos t ]]

我写的代码:

type Vector a = [a]
type Matrix a = [Vector a]
vectorToComplex :: Integral a => Vector a -> Vector (Complex Double)
vectorToComplex = map (\i -> fromIntegral i:+0.0)

matrixToComplex :: Integral a => Matrix a -> Matrix (Complex Double)
matrixToComplex = map vectorToComplex
--Z Gate
gateZ :: Matrix (Complex Double)
gateZ = matrixToComplex [[1,0],[0,-1]]

我尝试以与实现Z-gate相同的方式实现gateR(旋转门):

gateR :: Integral t => t -> Matrix (Complex Double)
gateR t = matrixToComplex [[cos t,-sin t],[sin t,cos t]]

但是我有下一个错误而且我并不理解它(我还在学习语言)。

Could not deduce (Floating t) arising from a use of `cos'
    from the context (Integral t)
      bound by the type signature for
                 gateR :: Integral t => t -> Matrix (Complex Double)
      at quantum.hs:66:8-44
    Possible fix:
      add (Floating t) to the context of
        the type signature for
          gateR :: Integral t => t -> Matrix (Complex Double)
    In the expression: cos t
    In the expression: [cos t, - sin t]
    In the first argument of `matrixToComplex', namely
      `[[cos t, - sin t], [sin t, cos t]]'

2 个答案:

答案 0 :(得分:10)

cossin只能使用Floating参数,但gateR的类型签名表示tIntegral类型,并非所有Integral都是Floating。使用gateR更改t的类型签名或转换gateR内的fromIntegral

答案 1 :(得分:4)

您的函数只需要Integral t的约束,因此您需要将tfromIntegral以及可能的显式类型签名进行转换,以便您可以应用正弦和余弦。 E.g。

cos (fromIntegral t :: Double)