2016-10-11 73 views
0

我有以下信息。它只是简单地检查List是否为空。但是,如果我尝试使用main运行它,则会出现错误。如何更改main函数以正确运行?数据列表 - 检查列表是否为空

data List a = Nil | Cons a (List a) 

vnull :: List a -> Bool 
vnull Nil = True 
vnull _ = False 

main = do print (vnull [1,2]) 

误差如下:

Couldn't match expected type `List a0' with actual type `[Integer]' 
    In the first argument of `vnull', namely `[1, 2]' 
    In the first argument of `print', namely `(vnull [1, 2])' 
    In a stmt of a 'do' block: print (vnull [1, 2]) 
+2

'print'需要你加上'以数据宣告结束了'List' – Michael

+3

无关尖获得Show':如果你不需要'do'只有一个'IO'动作(在你的情况下,'打印')。 – duplode

+4

btw。'这样做时'fromList = foldr Cons Nil'是一个非常方便的函数。 – epsilonhalbe

回答

1

更改为:

main = print $ vnull $ Cons 1 $ Cons 2 Nil 

生产:

False 
1

它正在像它被实现:

vnull Nil 
True 

vnull (Cons 1 Nil) 
False 

vnull (Cons 2 (Cons 1 Nil) 
False 

... 

,你可以尝试在ghci下面的命令,让所有有关[]数据类型:

Prelude> :t [] 
[] :: [t] 
Prelude> :i [] 
data [] a = [] | a : [a] -- Defined in ‘GHC.Types’ 
instance Eq a => Eq [a] -- Defined in ‘GHC.Classes’ 
instance Monad [] -- Defined in ‘GHC.Base’ 
instance Functor [] -- Defined in ‘GHC.Base’ 
instance Ord a => Ord [a] -- Defined in ‘GHC.Classes’ 
instance Read a => Read [a] -- Defined in ‘GHC.Read’ 
instance Show a => Show [a] -- Defined in ‘GHC.Show’ 
instance Applicative [] -- Defined in ‘GHC.Base’ 
instance Foldable [] -- Defined in ‘Data.Foldable’ 
instance Traversable [] -- Defined in ‘Data.Traversable’ 
instance Monoid [a] -- Defined in ‘GHC.Base’ 

为你的函数适用于[]参数,你需要这样的东西:

vnull :: [a] -> Bool 
vnull [] = True 
vnull _ = False 
-1

您可以: instance Foldeable List where foldMap f Nil = mempty foldMap f (Cons x ls) = mappend (f x) (foldMap ls) 然后使用(fold [1,2])::List Int

+0

该课程被称为'可折叠'。更重要的是,它的“折叠”方法并不符合你的要求。 – dfeuer

0
List a 

[] 

是两个不同的构造函数,而不是相同的数据类型,该函数将工作一类型名单,所以不是“[]”试试这个:

vnull :: List a -> Bool 
vnull Nil = True 
vnull (Cons a expand) = False 

然后

main = do print (vnull $ Cons 1 (Cons 2 Nil)) --This is just an example you can throw in a -List a- type of any length. 

而这应该解决它。

1

如果您希望能够使用您的List类型和通常的列表语法,那么您必须使用GHC扩展。

{-# LANGUAGE OverloadedLists, TypeFamilies #-} -- at the very top of the file 

import qualified GHC.Exts as E 
import Data.Foldable 

data List a = Nil | Cons a (List a) deriving (Show, Eq, Ord) 

instance Foldable List where 
    foldr _ n Nil = n 
    foldr c n (Cons x xs) = x `c` foldr c n xs 

instance E.IsList List where 
    type Item (List a) = a 

    fromList = foldr Cons Nil 
    toList = toList 
0

这是你错过了什么:

data List a = Nil | Cons a (List a) deriving Show 

fromList = foldr Cons Nil 

vnull :: List a -> Bool 
vnull Nil = True 
vnull _ = False 

main = do print (vnull $ fromList [1,2]) 

,导出显示现在是没有必要的,但将是,当你真正要打印列表,而不是一个布尔。 fromList函数什么也不做,但是要将Haskell Listimplementation(这里[1,2])转换成你自己的,所以你可以调用vnull。你可能还要求

main = do print $ vnull (Cons 1 (Cons 2 (Nil)))