{-# LANGUAGE DefaultSignatures #-}
class (Eq a) => Foo a where
size :: a -> Int
(==) :: a -> a -> Bool
(==) s t = (size s) == (size t)
(请注意,我已经包含了上述问题的解决方案中建议的语言扩展)
我收到以下ghci错误消息:
Ambiguous occurrence â==â
It could refer to either âMain.==â,
defined at permutations.lhs:162:3
or âPrelude.==â,
imported from âPreludeâ at permutations.lhs:1:1
(and originally defined in âGHC.Classesâ)
我是想在哈斯克尔做些不可能的事吗?我知道我可以做一些类似的事情
class (Eq a) => Foo a where
size :: a -> Int
data Bar = Qux [Int]
instance Foo Bar where
size (Qux xs) = length xs
instance Eq Bar where
(==) f g = (size f) == (size g)
但我必须复制
(==)
对于的每个实例
Foo
,而不是将其作为默认定义。
我也意识到如果我用自己的超类而不是
等式
,我本可以写
class Bam a where
eqs :: a -> a -> Bool
default eqs :: Roo a => a -> a -> Bool
eqs f g = (size f) == (size g)
class (Bam a) => Roo a where
size :: a -> Int
{-# LANGUAGE DefaultSignatures #-}
module My where
class (Eq a) => Foo a where
size :: a -> Int
(==) :: a -> a -> Bool
(==) s t = (size s) Prelude.== (size t)
instance Eq a => Foo [a] where
size = length
main :: IO ()
main = do
print $ a Prelude.== b
print $ a My.== b
where
a = [1, 2, 3]
b = [3, 4, 5]