Haskell无法将预期类型“ Item Nat”与实际类型“()”匹配

时间:2018-12-31 13:13:49

标签: class haskell

我已收到此源代码。

data Nat = Zero | Succ Nat deriving Show
class FromList a where
  type Item a :: *
  fromList :: [Item a] -> a

我应该编写函数fromList,以便它像这样进行转换,例如:

fromList [(),(),()] :: Nat
===> Succ (Succ (Succ Zero))

我的代码是

instance FromList Nat where
  fromList [] = Zero
  fromList (a:as) = Succ (fromList as :: Nat)

如果我使用fromList [] :: Nat,那么答案就是Zero,所以它是正确的 但是当我使用fromList [(),(),()] :: Nat时,出现错误消息:

Couldn't match expected type ‘Item Nat’ with actual type ‘()’
    • In the expression: ()
      In the first argument of ‘fromList’, namely ‘[(), (), ()]’
      In the expression: fromList [(), (), ()] :: Nat

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

您需要为实现的类型Item t的每个实例定义t。换句话说,这可以通过添加一行来解决

instance FromList Nat where
  type Item Nat = ()
  fromList [] = Zero
  fromList (a:as) = Succ (fromList as :: Nat)

现在Item Nat()不可更改,不会发生错误。