Haskell无法推断类型?

我已经尝试过无数的Google搜索答案,但是对于Haskell来说还很陌生,我不了解所发现的一半内容,而另一半却与之并没有什么联系。

我的问题是,如果我在ghci中运行这些语句

Prelude> let x = 5 :: (Num a) => a
Prelude> sqrt x

我得到了我所期望的

2.23606797749979

但是,如果我将其放入文件中并进行编译(当然,我在这里所做的工作非常琐碎)

sqrtNum :: (Num a, Floating b) => a -> b
sqrtNum x = sqrt x

我明白了

myfile.hs:2:18:
    Could not deduce (a ~ b)
    from the context (Num a, Floating b)
      bound by the type signature for
                 sqrtNum :: (Num a, Floating b) => a -> b
      at test2.hs:1:12-40
      `a' is a rigid type variable bound by
          the type signature for sqrtNum :: (Num a, Floating b) => a -> b
          at test2.hs:1:12
      `b' is a rigid type variable bound by
          the type signature for sqrtNum :: (Num a, Floating b) => a -> b
          at test2.hs:1:12
    Relevant bindings include
      x :: a (bound at test2.hs:2:9)
      sqrtNum :: a -> b (bound at test2.hs:2:1)
    In the first argument of `sqrt', namely `x'
    In the expression: sqrt x

该问题可能非常简单,我只是对其进行了监督(因此,我遇到的所有其他错误都是我的经验),但这并不是单击。

提前致谢!

Bzzt

您要说的是您有一个从Num a到Floating b的函数。sqrt函数需要Floating类型作为输入,但是您仅保证Num。这是sqrt的类型:

Main> :t sqrt
sqrt :: Floating a => a -> a

因此,让我们复制sqrt并将其从浮动变为浮动:

sqrtNum :: (Num a, Floating a) => a -> a
sqrtNum x = sqrt x

尽管只需要浮动,但我离开了Num。浮点数是小数,而小数是数字。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章