0
votes

I'm just starting out with Haskell and I want to define a type like this :

data Point = Int | [Int]

ie. at any Point I want to store either a single integer or a list of integers. (Ultimately I'm going to store these Points in a list)

For some reason it tells me there's a parse error at the [Int].

What am I misunderstanding?

2

2 Answers

7
votes

You need a value constructor for each "option" in your data type, so that you can determine whether you have a single Int or a list of Int. For example:

data Point = Single Int | Many [Int]

Then you can pattern-match on values of this Point type:

examine :: Point -> String
examine (Single x) = "One: " ++ show x
examine (Many xs) = "Many: " ++ show xs

Your original declaration is illegal because otherwise there would be no way to use Point values, not knowing what they hold.

6
votes

A data type definition consists of one or more constructor definitions separated by |. A constructor definition is an identifier that starts with a capital letter, followed by zero or more type names.

So Int is a valid constructor definition because it's an identifier that starts with a capital letter. However it defines a constructor of zero arguments and is not in any way related to the Int type. So that's not what you want. If you want a constructor that contains a value of type Int, it should be something like Single Int, which would define a constructor named Single that takes an Int.

[Int] is not a valid constructor definition because it doesn't start with an identifier. You probably want something like Many [Int]. That would define a constructor named Many that takes a list of Ints.