以下类型签名来查找表示为元组的向量的大小似乎不起作用:
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)
最佳答案
计算类型签名的一种方法是要求编译器为您进行类型推断:
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
关于haskell - 输入函数的签名来查找向量的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5688170/