哈斯克尔。使用约束来定义类的实例

时间:2015-04-15 20:06:19

标签: class haskell instance

在尝试理解Haskell中的实例时,我做了这个例子。整数部分运行良好,但它不适用于Float实例。我认为最好制作Num类型的单个实例(这样正方形适用于所有Num)。我想我必须添加Num作为我的类声明的约束,但我无法弄清楚实例的样子。据我了解,类的约束强制任何实例属于该类型(根据约束)。

class Square a where
    area :: a -> a

instance Square Integer where
    area a = a*a

instance Square Float where
    area a = a*a

1 个答案:

答案 0 :(得分:10)

  

我认为最好制作Num ...

类型的单个实例

不是真的,除非你想为Num类型定义类(然后你根本不需要一个类,只需要它{{1} }作为顶级函数。)

以下是制作此类通用实例的方法:

area :: Num a => a->a

这不是Haskell98,但它确实适用于广泛使用的instance (Num a) => Square a where area a = a*a -XFlexibleInstances扩展。

问题:如果你还想添加,比方说,

-XUndecidableInstances

您有两个重叠实例。这是一个问题:通常,编译器无法确定两个这样的实例中哪一个是正确的。同样,GHC可以做出最佳猜测(instance Square String where area str = concat $ replicate (length str) str -XOverlappingInstances),但与-XIncoherentInstances不同,这些是generally avoided

因此,我 建议制作单个实例Flexible/UndecidableInstancesSquare IntSquare Integer。他们不是很难写,是吗?