class - haskell 。使用约束来定义类的实例

标签 class haskell instance

在尝试理解 Haskell 中的实例时,我做了这个例子。 Integer 部分工作良好,但不适用于 Float 实例。我认为最好创建 Num 类型的单个实例(以便 square 适用于所有 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

最佳答案

I think it is better to make a single instance of the type 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 不同,它们是 generally avoided .

因此,我建议创建单独的实例Square IntSquare IntegerSquare Double。它们并不难写,不是吗?

关于class - haskell 。使用约束来定义类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29659866/

相关文章:

Javascript:当事件处理程序是对象的多个实例时如何从事件处理程序中获取对象的正确实例

ios - 在 Swift 中以编程方式更改 Storyboard 的类

haskell - Haskell 和 PureScript 有什么区别?

python - 构造一个类来展平 python 列表

haskell - 在 Haskell 中使用自定义二进制数据类型是个坏主意吗?

unix - 在 haskell 中实现 unix 管道

mysql - MySql 5.6 相当于 `MySQLInstanceConfig.exe` 在哪里编辑配置文件?

azure - Windows Azure 上的 Web 角色和 iisreset 副作用

c++ - 在C++中初始化对象中的数组

c# - 如何获取 iTextSharp.text.pdf.parser.Vector 对象的 x、y、z 值?