I want to construct a new data type called Oct, and it should return 1 or 2 or 3, so my code is something like this : data Oct = 1|2|3
but the Haskell shows the error like this: Cannot parse data constructor in a data/newtype declaration: 1
And I don`t know what does this error means. how should I fix it?
You can't really make arbitrary subtypes like that. What you can do is make a data type with three constructors, you just have to understand some things about data declarations:
When you declare a new data type, you declare it with its constructors. The constructors you use are brand new names that don't already have a meaning. The datatype and its constructors must all begin with a capital letter. So you say
data Oct = One | Two | Three
This declares the type Oct
and three values One
, Two
, and Three
-- four declarations at once.
Another alternative is to use a smart constructor with a type like
newtype Oct = Oct Int
as shown in more detail in @Nawaz's answer.
There is a way to make numeric literals work, so you can use 1 :: Oct
, but for this case it's not good because (the way the libraries are designed) numeric literals ought to come with numeric structure as well, which Oct
doesn't have (well, unless you want to start doing fancy math). Also using 4 :: Oct
would typecheck but would be a runtime error, which we also don't like.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With