How can I add input checks to Haskell data constructors? Let’s say I have
import Data.Time.Calendar
data SchedulePeriod = SchedulePeriod { startDate :: Day
, endDate :: Day
, accrualStart :: Day
, accrualEnd :: Day
, resetDate :: Day
, paymentDate :: Day
, fraction :: Double }
deriving (Show)
and I want to impose a constraint startDate < endDate. Is there a way to do it without creating an abstract data type?
The standard way is to use a smart constructor that checks the precondition before creating the value, and to not export the real constructor it uses. Of course, this is creating an abstract data type, as you said.
The only way to achieve this without a smart constructor would be really evil type-system hackery (and you wouldn’t be able to use the standard
Daytype).