data List - 检查列表是否为空

时间:2016-10-11 13:31:21

标签: list haskell syntactic-sugar

我有以下内容。它只是检查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])

6 个答案:

答案 0 :(得分:1)

更改为:

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

产生

False

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分: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. 

这应该解决它。

答案 4 :(得分: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])

现在不需要派生Show,但是当你真正想要打印List而不是Bool时。 fromList函数什么都不做,但是要将Haskell Listimplementation(这里[1,2])转换成你自己的,所以你可以在它上面调用vnull。你也可以打电话给

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

答案 5 :(得分:-1)

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