Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell, How could I construct a new datatype so that the value of that type is 1 or 2 or 3?

Tags:

haskell

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?

like image 525
Junhan Liu Avatar asked Dec 10 '22 10:12

Junhan Liu


1 Answers

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.

like image 126
luqui Avatar answered May 25 '23 16:05

luqui