Haskell无法获得我的功能依赖项

问题描述 投票:2回答:2

我正在尝试创建一个实现基本队列行为的队列类型类。我的代码如下:

{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}

data QueueA a = QueueA { front :: [a], rear :: [a] }

class Queue a b | a -> b where

  empty         :: a
  null          :: a -> Bool
  head          :: a -> Maybe b
  tail          :: a -> Maybe a
  toList        :: a -> [b]
  (|>)          :: a -> b -> a

instance Queue (QueueA a) where      

  empty = QueueA [] []

  null (QueueA [] []) = True
  null _ = False

  head (QueueA [] []) = Nothing
  head (QueueA (x:xs) _) = Just x

  tail (QueueA [] []) = Nothing
  tail (QueueA (x:xs) (y:ys)) = Just $ QueueA (xs ++ [y]) ys

  toList (QueueA x y) = x ++ y

  (|>) (QueueA x y) e = if (length x > length y) then QueueA (init $ e : x) ((last x) : y) else QueueA (e : x) y

不幸的是,当我尝试编译代码时,ghc告诉我以下内容:

queue.hs:15:10: error:
    • Expecting one more argument to ‘Queue (QueueA a)’
      Expected a constraint,
        but ‘Queue (QueueA a)’ has kind ‘* -> Constraint’
    • In the instance declaration for ‘Queue (QueueA a)’
   |
15 | instance Queue (QueueA a) where 
   |          ^^^^^^^^^^^^^^^^

虽然我没有真正收到消息。我所知道的是,实例声明中的Queue模式必须正确,因为它正是我在上面的数据类型中指定的模式。我尝试了实例声明的几种变体,但没有成功。我只是在俯视什么吗?如何使它可编译?

haskell constraints typeclass functional-dependencies
2个回答
2
投票

该类不需要多个参数。相反,该类应采用高阶类型作为其参数,而不是具体类型。

class Queue t where
    empty :: t a
    null :: t a -> Bool
    head :: t a -> Maybe a
    tail :: t a -> Maybe (t a)
    toList :: t a -> [a]
    (|>) :: t a -> a -> t a

[QueueA本身具有Queue实例,而不是QueueA a

instance Queue QueueA where
  -- same as above

4
投票

实例需要与相应类相同数量的参数。但是,您创建了一个具有2个参数的类,以及一个仅包含1个实例的对应实例。要进行编译,可以执行instance Queue (QueueA a) a where而不是instance Queue (QueueA a) where。 (您还需要FlexibleInstances扩展名。)

© www.soinside.com 2019 - 2024. All rights reserved.