繁体   English   中英

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

[英]Haskell. Using constraint to define an instance of a class

在尝试理解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

我认为最好制作Num类型的单个实例...

不是真的,除非你想Num类型定义那个类(然后你根本不需要一个类,只需要将它作为area :: Num a => a->a作为顶级函数)。

这是制作这样一个通用实例的方法:

instance (Num a) => Square a where
  area a = a*a

这不是Haskell98,但它确实适用于广泛使用的-XFlexibleInstances-XUndecidableInstances扩展。

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

instance Square String where
  area str = concat $ replicate (length str) str

你有两个重叠的实例 这是一个问题:通常,编译器无法确定哪两个这样的实例是正确的。 同样,GHC具有进行最佳猜测的扩展( -XOverlappingInstances-XIncoherentInstances ),但与Flexible/UndecidableInstances不同,这些通常是避免的

因此, 建议让单独的实例Square IntSquare IntegerSquare Double 他们不是很难写,不是吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM