我正在学习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]]'
答案 0 :(得分:10)
cos
和sin
只能使用Floating
参数,但gateR
的类型签名表示t
是Integral
类型,并非所有Integral
都是Floating
。使用gateR
更改t
的类型签名或转换gateR
内的fromIntegral
。
答案 1 :(得分:4)
您的函数只需要Integral t
的约束,因此您需要将t
与fromIntegral
以及可能的显式类型签名进行转换,以便您可以应用正弦和余弦。 E.g。
cos (fromIntegral t :: Double)