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

Man*_*anu 2 polymorphism haskell typeclass

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

mag :: (Floating b, Num a) => (a,a) -> b
mag (x,y) = sqrt (x**2 + y**2)
Run Code Online (Sandbox Code Playgroud)

错误:

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)
Run Code Online (Sandbox Code Playgroud)

Don*_*art 5

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

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

Prelude> :t mag
mag :: Floating a => (a, a) -> a
Run Code Online (Sandbox Code Playgroud)

这可能是你想要的类型.


现在,你的类型需要一对a并以某种方式将它们转换为Num类中的ab .你的意思是转换到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
Run Code Online (Sandbox Code Playgroud)