2011-04-16 63 views
2

以下類型簽名的幅度找表示爲一個元組向量的大小似乎不工作:函數的類型簽名來找到一個向量

mag :: (Floating b, Num a) => (a,a) -> b 
mag (x,y) = sqrt (x**2 + y**2) 

錯誤:

計算一個類型簽名
Couldn't match expected type `b' against inferred type `a' 
    `b' is a rigid type variable bound by 
     the type signature for `mag' at tone.hs:1:17 
    `a' is a rigid type variable bound by 
     the type signature for `mag' at tone.hs:1:24 
In the expression: sqrt (x ** 2 + y ** 2) 
In the definition of `mag': mag (x, y) = sqrt (x ** 2 + y ** 2) 

回答

5

一種方法是要求編譯器做的類型推斷你:

Prelude> let mag (x,y) = sqrt (x**2 + y**2) 

Prelude> :t mag 
mag :: Floating a => (a, a) -> a 

氏s可能是你想要的類型。


現在,你的類型需要一對的,並以某種方式將它們轉換成在Num類A B。你的意思是轉換到更一般的Num班嗎?如果是這樣,你需要truncate或類似的東西,和fromIntegral

我的猜測是,這是不是你想要的,但你可以做到這一點,

Prelude> let mag (x,y) = fromIntegral . truncate $ sqrt (x**2 + y**2) 

Prelude> :t mag 
mag :: (Floating a, RealFrac a, Floating a) => (a, a) -> c 
+0

是的,我的意思是有一個轉換那裏。並且,謝謝,fromIntegral像魅力一樣工作(沒有截斷)。 – Manu 2011-04-16 17:36:35

+0

要求是對兩個積分數有浮點數。 fromIntegral和(Floating b,Integral a)的使用有效。 – Manu 2011-04-16 17:44:23

+0

風格點:大多數Haskell不會像其他語言那樣在括號中放置參數;這通常具有類型「mag :: a - > a - > a」。我可以看到,在這裏你可能想把一個向量看作一個(x,y)對,所以一個元組是有意義的。但是在這種情況下,您應該使用類型同義詞來記錄它:「type Vector a =(a,a)」 – 2011-04-16 19:53:18

相關問題