键入函数的签名以查找向量的大小

时间:2011-04-16 17:10:02

标签: haskell polymorphism typeclass

以下类型签名用于查找表示为元组的向量的大小似乎不起作用:

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)

1 个答案:

答案 0 :(得分:5)

计算类型签名的一种方法是让编译器为您做类型推断:

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

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

这可能是你想要的类型。


现在,你的类型需要一对a并以某种方式将它们转换为Num类中的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