Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a type bounded within a certain range

Tags:

I would like to create a new integral type which is bounded to a certain range. I have tried:

data PitchClass = PC Int deriving (Ord, Eq, Show)  instance Bounded PitchClass where   minBound = PC 0   maxBound = PC 11 

However, what I want is something that will fail if something like

PC 12 

or

PC (-1) 

is attempted.

Is the general approach for a situation in which you wish to place constraints on creating new types one in which the value constructors are not exported from the module, but rather functions which return instances of the type and which perform constraint checks are exported?

like image 296
user268344 Avatar asked Sep 04 '11 23:09

user268344


People also ask

How do I restrict a generic type in Java?

Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.

Which of these is the correct way to declare a bounded type?

To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number .

Can a parameterized type have several bounds?

A type parameter can have multiple bounds.

What are bounded type why it is used give example?

Using bounded types, you can make the objects of generic class to have data of specific derived types. For example, If you want a generic class that works only with numbers (like int, double, float, long …..) then declare type parameter of that class as a bounded type to java.


1 Answers

Yes, not exporting the data constructor from the module is the way to go.

Instead, you export a function which does the checking as you said. This is often called a smart constructor.

like image 111
hammar Avatar answered Sep 20 '22 08:09

hammar