0

这是一个关于 Data.List.Class 使用问题的问题(与Haskell Data.List.Class and syntax的上一个问题有关)。

下面列出了代码的相关部分。据我了解,这个类提供了一个类型类接口或对 Haskell 列表类型的泛化,这可能非常有用。但是,我真的找不到太多关于这个类的使用的文档。有谁知道好的教程吗?

另外,我有一个关于它的用法和类型的技术/具体问题。从代码中,我会认为在类型类定义中,runList 和 joinL 是相互的(在某种意义上)。

-- other stuff omitted
import Data.Functor.Identity (Identity(..))

data ListItem l a =
    Nil |
    Cons { headL :: a, tailL :: l a }

Data.List.Class
-- | A class for list types. Every list has an underlying monad.
class (MonadPlus l, Monad (ItemM l)) => List l where
    type ItemM l :: * -> *
    runList :: l a -> ItemM l (ListItem l a)
    joinL :: ItemM l (l a) -> l a
    cons :: a -> l a -> l a
    cons = mplus . return

instance List [] where
    type ItemM [] = Identity
    runList [] = Identity Nil
    runList (x:xs) = Identity $ Cons x xs
    joinL = runIdentity
    cons = (:)

fromList :: List l => [a] -> l a
fromList = foldr cons mzero

首先,我joinL $ runList [1, 2, 3]以emacs模式进入,但出现以下错误:

Couldn't match type `ItemM (ListItem [])' with `Identity'
Expected type: ItemM (ListItem []) (ListItem [] Integer)
  Actual type: ItemM [] (ListItem [] Integer)

正如它所说,预期和实际类型并不完全匹配。但我不明白为什么他们首先需要不同的类型。它们runList :: l a -> ItemM l (ListItem l a)joinL :: ItemM l (l a) -> l a含义或语义有何不同?

另外,我在emacs模式下尝试了一个非常简单的fromList函数,如下所示:fromList [1,2,3],但我得到了:

Ambiguous type variable `l0' in the constraint:
  (List l0) arising from a use of `fromList'
Probable fix: add a type signature that fixes these type variable(s)
In the expression: fromList [1, 2, 3]
In an equation for `it': it = fromList [1, 2, 3]

我在这里很困惑为什么这里有歧义,以及如何添加类型签名作为错误消息提示。谁能帮忙解释一下?

提前致谢,

4

1 回答 1

1

最后一个问题:实现List类型类的可能有好几种类型,如果后面不去推断,应该指定。例如fromList [1, 2, 3] :: [Int]工作正常。

于 2012-08-07T13:00:43.763 回答