haskell - 输入函数的签名来查找向量的大小

标签 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)

最佳答案

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

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/

相关文章:

haskell - 涉及函数组合的常见模式 (\a b -> f (g a) (g b))

multithreading - GHC 每线程 GC 策略

java - 从基类请求主体 DTO 获取派生 DTO

java方法重载继承与多态

scala - 是否可以使用类型类来实现特征?

haskell - Haskell 守卫是如何评估的?

haskell - 在 Haskell 中将 foldr 与 OR 混合(懒惰?)

ios - Swift 2.0 中的协议(protocol)扩展方法分派(dispatch)

haskell - 类型线程异构列表和类型族默认(?)?

haskell - 从运算符推断类型类别