2011-04-16 64 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

相关问题