从Haskell中的Integer重载 [英] Overriding fromInteger in Haskell

查看:164
本文介绍了从Haskell中的Integer重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我喜欢Haskell,但对Num类不满意。
所以我想为代数类型创建自己的类型类层次结构。

问题是,即使我导入Prelude隐藏Num及其相关的所有东西,仍然是唯一的方法来创建字面值1有类型t就是让t实例Num。

我很乐意从Integer类中创建我自己的类,并将Num完全抛出图片,就像这样

  import Prelude隐藏(一切与Num有关)
导入合格的Prelude(所有与Num有关的)

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

foo ::(FromInteger fi)=> fi - >字符串
foo 1 =那是一个
foo 0 =那是零
foo n =既不是零也不是一个

,然后我将适当地实施fromInteger以获取全新的类型,而不必对Num进行任何说明。



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



谢谢!

解决方案

您正在寻找GHC的 RebindableSyntax扩展



通过放置$ / b来启用它
$ b

  { - #LANGUAGE RebindableSyntax# - } 

放在源文件的顶部。


So I like Haskell, but am dissatisfied with the Num class. So I want to make my own typeclass hierarchic for algebraic types.
The problem is, even if I import Prelude hiding Num and everything associated with it, still the only way to make the literal 1 have type t is to make t instance Num.
I would love to make my own fromInteger class and leave Num out of the picture entirely, like this

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"

and then I would implement fromInteger appropriately for brand new types and never have to say anything about Num.

Is there a way to tell the parser to use a different fromInteger method?

Thanks!

解决方案

You are looking for GHC's RebindableSyntax extension.

Enable it by putting

{-# LANGUAGE RebindableSyntax #-}

at the top of your source file.

这篇关于从Haskell中的Integer重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆