For a data type constructor, is there any way to limit the creation of the "object" (I don't know the proper term) based on criteria other than the types of the arguments to the constructor?
For instance:
data UInt = UInt Int --the int must be >= 0
Truly, I would like to create a data type for rectangular multidimensional lists (in which all the sublists have the same length). Would a class or some other technique be better suited for this?
No, there is no way to enforce what values a user passes to a constructor.
However, there is a common practice in the community and standard library of creating smart constructors. You see these in modules like Data.Map
, Data.Ratio
, and many more. Simply put, you don't export the constructor itself, just the type, and you export a function which vets the arguments:
module UInt
( UInt
, uint
) where
data UInt = UInt Int
uint :: Int -> Maybe UInt
uint x | x >= 0 = Just (UInt x)
| otherwise = Nothing
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