简体   繁体   中英

List syntax with custom list type

Given a custom type of lists such as

data List' a = EmptyList | NonEmptyList a (List' a)
           deriving Show

and a function to tell if such a list is non-empty

null' xs = case xs of
  EmptyList -> True
  _ -> False

why doesn't calling it in GHCi with list arguments like

null' NonEmptyList [1,2,3] 

or

null' EmptyList []

work? Calling the function with the constructors defined does work.

null' Emptylist

Why is this?

Like shachaf mentioned, your list type is not the same as Haskell's list type provided in the Prelude. That means that you cannot use list bracket syntax for your custom list type unless you use the OverloadedLists language extension, which you can read more about here .

However, let's assume for a moment that you don't overload list syntax. Then the only way you can invoke your null' function is with the constructors you defined:

>>> null' EmptyList
True
>>> null' (NonEmptyList 1 (NonEmptyList 2 EmptyList))
False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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