在Haskell中将类型类包含在默认实现中 [英] Inclusion of typeclasses with default implementation in Haskell

查看:59
本文介绍了在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")

顺便说一句,如果有帮助,我可以用其他方式定义我的FooBar类.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆