【问题标题】:Overriding fromInteger in Haskell在 Haskell 中覆盖 fromInteger
【发布时间】:2012-12-20 18:37:27
【问题描述】:

所以我喜欢 Haskell,但对 Num 类不满意。 所以我想为代数类型创建自己的类型类层次结构。
问题是,即使我导入 Prelude 隐藏 Num 以及与之相关的所有内容,仍然使文字 1 具有类型 t 的唯一方法是使 t 实例 Num。
我很想创建自己的 fromInteger 类,并完全将 Num 排除在外,就像这样

import Prelude hiding (everything having to do with Num)
import qualified Prelude (everything having to do with Num)

class (Eq fi) => FromInteger fi where
  fromInteger :: Integral -> fi

foo :: (FromInteger fi) => fi -> String
foo 1 = "that was a one"
foo 0 = "that was a zero"
foo n = "that was neither zero nor one"

然后我会为全新的类型适当地实现 fromInteger,而不必对 Num 说任何话。

有没有办法告诉解析器使用不同的 fromInteger 方法?

谢谢!

【问题讨论】:

    标签: haskell numeric typeclass


    【解决方案1】:

    您正在寻找 GHC 的RebindableSyntax extension。

    通过放置来启用它

    {-# LANGUAGE RebindableSyntax #-}
    

    在源文件的顶部。

    【讨论】:

    • @JosephVictor 也请查看Numeric Prelude。您可能会发现它可以满足您的需求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    相关资源
    最近更新 更多