0
votes

I'm trying to create a data type class that contains a list:

data Test = [Int] deriving(Show)

But Haskell can't parse the constructor. What am i doing wrong here and how can I best achieve what I'm trying to do?

1
The data constructor name is missing. You want something like data Test = Test [Int] instead.duplode
you also probably want a newtype rather than data if your type is simply a wrapper for a listRobin Zigmond
newtype still needs a data constructor name in front of the [Int].Will Ness
yes of course @WillNess, apologies if that wasn't clearRobin Zigmond
I was reading Learn You A Haskell for Great Good. The examples on chapter 7 didn't include lists and some didn't have the constructor name. Should probably have fiddled around with it a bit more before asking, but anyway I have it working with newtype now.Ultimate Gobblement

1 Answers

8
votes

An Answer

You need to include a constructor, which you haven't done.

data Test = Test [Int]

Consider reviewing Haskell's several type declarations, their use, and their syntax.

Haskell Type Declarations

data

Allows declaration of zero or more constructors each with zero or more fields.

newtype

Allows declaration of one constructor with one field. This field is strict.

type

Allows creation of a type alias which can be textually interchanged with the type to the right of the equals at any use.

constructor

Allows creation of a value of the declared type. Also allows decomposition of values to obtain the individual fields (via pattern matching)

Examples

data

data Options = OptionA Int | OptionB Integer | OptionC PuppyAges
      ^           ^     ^      ^        ^        ^         ^
      |           |   Field    |        |        |         |
    type         Constructor   |        |     Constructor  |
                         Constructor   Field              Field
    deriving (Show)

myPuppies = OptionB 1234

newtype

newtype PuppyAges = AgeList [Int] deriving (Show)

myPuppies :: PuppyAges
myPuppies = AgeList [1,2,3,4]

Because the types (PuppyAges) and the constructors (AgeList) are in different namespaces people can and often do use the same name for each, such as newtype X = X [Int].

type

type IntList = [Int]

thisIsThat :: IntList -> [Int]
thisIsThat x = x

constructors (more)

option_is_a_puppy_age :: Options -> Bool
option_is_a_puppy_age (OptionC _) = True
option_is_a_puppy_age () = False

option_has_field_of_value :: Options -> Int -> Bool
option_has_field_of_value (OptionA a) x = x == a
option_has_field_of_value (OptionB b) x = fromIntegral x == b
option_has_field_of_value (OptionC (AgeList cs)) x = x `elem` cs

increment_option_a :: Options -> Options
increment_option_a (OptionA a) = OptionA (a+1)
increment_option_a x           = x