繁体   English   中英

为数据类型列表创建实例-Haskell

[英]Create instance for list of data types - Haskell

我觉得这应该真的很容易,但是我在这一点上停留了很长时间。

在haskell中是否可以为某些数据类型的列表创建类型类的实例?

我要实现的是以下内容。

class Rename a where
    findSub :: a -> a

-- A 'normal' instance would look like this
instance Rename Atom where
    findSub ......

-- Now i want to acchieve something like this
instance Rename ([] Atom) where
    findSub ......

但是当我写这篇文章时,却遇到以下错误:

* Illegal instance declaration for `Rename [Atom]'
        (All instance types must be of the form (T a1 ... an)
         where a1 ... an are *distinct type variables*,
         and each type variable appears at most once in the instance head.
         Use FlexibleInstances if you want to disable this.)
    * In the instance declaration for `Rename ([] Atom)'
Failed, modules loaded: none.

我想知道如何解决此问题以及为什么不允许这样做。

提前致谢。

它仅需要语言扩展,因为Haskell 98标准在技术上不允许这种形式的实例。 当错误消息显示要启用扩展时,通常只需执行[1]。 FlexibleInstances是一个非常普遍且可以接受的扩展,因此只需输入

{-# LANGUAGE FlexibleInstances #-}

在文件的顶部。


另外,通常可以“递归”定义此类实例,在这种情况下,您不需要扩展,但除此之外,您可以免费获得更多实例,并且由于类型更通用,因此可以提供更多保证。 看看是否可以定义

instance (Rename a) => Rename [a] where
    findSub ...

相反,仅使用aRename的事实,而不是专门使用Atom 当您可以通过这种方式定义实例时,这是设计正确的好兆头。


[1]有一些例外,例如UndecidableInstancesIncoherentInstances ,这有时表明您对类型类解析的工作原理有错误的认识。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM