Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform checks on data type construction

Tags:

haskell

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?

like image 509
Mark Anastos Avatar asked May 17 '16 19:05

Mark Anastos


1 Answers

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
like image 114
bheklilr Avatar answered Sep 27 '22 20:09

bheklilr