在尝试理解 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 Int
、Square Integer
、Square Double
。它们并不难写,不是吗?
关于class - haskell 。使用约束来定义类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29659866/