在Haskell中将类型类包含在默认实现中 [英] Inclusion of typeclasses with default implementation in Haskell
问题描述
请考虑以下定义:
class Foo a where
foo :: a -> Int
class Bar a where
bar :: a -> [Int]
现在,如何在Haskell中怎么说每个Foo
也是Bar
,默认情况下bar
定义为bar x = [foo x]
"
Now, how do I say "every Foo
is also a Bar
, with bar
defined by default as bar x = [foo x]
" in Haskell?
(无论尝试什么,编译器都会给我非法实例声明" 或约束不小于实例头" )
(Whatever I try, the compiler gives me "Illegal instance declaration" or "Constraint is no smaller than the instance head")
顺便说一句,如果有帮助,我可以用其他方式定义我的Foo
和Bar
类.
Btw, I can define my Foo
and Bar
classes in some other way, if this would help.
推荐答案
由于通过Foo
实例对Bar
实例的自动定义可能导致编译器发生无法确定的情况-即一个显式实例和一个通过Foo
彼此冲突-,我们需要一些特殊的选项来允许期望的行为.其余的工作都非常有力.
As the automatic definition of a Bar
instance through a Foo
instance can lead to undecidable cases for the compiler - i.e. one explicit instance and one through Foo
conflicting with each other - , we need some special options to allow the desired behaviour. The rest through is quite straigtforward.
{-# LANGUAGE FlexibleInstances, UndecidableInstances #-}
class Foo a where
foo :: a -> Int
class Bar a where
bar :: a -> [Int]
instance (Foo a) => Bar a where
bar x = [foo x]
这篇关于在Haskell中将类型类包含在默认实现中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!