2016-08-12 39 views
1

我在學習Haskell,我試圖根據我在互聯網上找到的資源實現一些量子門。 現在,我成功實現了Z-gate,X-gate,H-gate,但是我在實現旋轉門時遇到了問題。Haskell:無法推斷(浮動t)由於使用'cos'引起

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-門:

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]]' 

回答

9

cossin只能採取Floating的說法,但對於gateR類型簽名說tIntegral類型,並且不是所有Integral s爲Floating。請使用fromIntegral更改gateR的型號簽名或在gateR之內轉換t

4

您的功能只需要約束Integral t,因此您需要將您的t轉換爲fromIntegral,並且可能需要一個明確的類型簽名,以便您可以應用正弦和餘弦。例如。

cos (fromIntegral t :: Double)