【问题标题】:Integer to Num conversion in HaskellHaskell 中的整数到 Num 转换
【发布时间】:2021-12-24 08:43:01
【问题描述】:

我只是在玩 Haskell 类型类,发现了一个我无法理解的错误。

这是重现它的代码:

fun :: (Num a) => Integer -> a
fun a = a + 1

错误:

Couldn't match expected type ‘a’ with actual type ‘Integer’

现在,据我了解,Integer 是 Num 类型类的instance,Integer 类型满足 Num 定义的所有要求。 这种转换是不允许的吗?这不是使用创建 Typeclass 的重点吗,即 'a' 是 typeclass Num 的任何实例。

【问题讨论】:

  • 在 Haskell 中没有隐式转换:Integer 不会自动提升为 Double -- 我们需要调用 fromInteger 来显式转换值。唯一的例外是数字文字:123 会自动转换为上下文所需的数字类型,本质上表现得好像用户写了fromInteger (123::Integer)。所有其他表达式(包括变量)都不受这种自动转换的影响。

标签: haskell types type-conversion typeerror


【解决方案1】:

(+) :: Num a => a -> a -> a 表示两个操作数和结果都具有相同的类型。因此,这意味着对于表达式a + 1,因为aInteger,这意味着1a + 1 也是Integers。

但是,您的函数承诺对于 any 类型 a (其中 Num a 成立),它可以构造一个函数,将 Integer 映射到该类型的对象 a。所以可以是IntegerIntDouble 等。

您可以使用fromInteger :: Num a => Integer -> a function 将结果转换为任何Num 类型:

fun :: Num a => Integer -> a
fun = fromInteger (a + 1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    相关资源
    最近更新 更多