繁体   English   中英

数据列表-检查列表是否为空

[英]data List - checking if a list is empty

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

更改为:

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

产生:

False

它像实现了一样工作:

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

如果您希望能够使用通常的列表语法使用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
List a

[]

是两个不同的构造函数,而不是相同的数据类型,该函数适用于List类型,因此请尝试使用“ [] ”代替:

 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. 

这应该可以解决。

这是您所缺少的:

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时,将需要Show。 fromList函数不执行任何操作,只是将Haskell Listimplementation(此处[1,2])转换为您自己的,因此您可以在其上调用vnull。 您可能还打电话

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM