[Haskell-beginners] Check constructor's field numeric value at compile time

Alexandre Lucchesi alexandrelucchesi at gmail.com
Tue Sep 2 20:58:24 UTC 2014


You can't do that within the data type declaration.

In order to add such constraints you should define "constructor functions"
and apply the validation there, i.e.:

newSecondsInterval :: Float -> Maybe Interval
newSecondsInterval n
  | n >= 1     = Just $ Seconds n
  | otherwise = Nothing

Note that the "Maybe" type is only a way to handle the case where the
supplied value is invalid. Also, in order to provide encapsulation and
ensure no one is going to create a new "Interval" by using "Seconds" and
"MicroSeconds", you should hide these value constructors in the export list
of your module.


On Tue, Sep 2, 2014 at 4:32 PM, Dmitriy Matrosov <sgf.dma at gmail.com> wrote:

> Hi.
>
> I have a type
>
> data Interval   = Seconds Float
>                 | MicroSeconds Int
>
> The Float field of data constructor Seconds should be >= 1, and Int field
> of constructor MicroSeconds should be in the range from 0 to 1000000.
>
> How can i write this constraints so they're checked at compile time, not
> at runtime?
>
> --
>     Dmitriy Matrosov
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>



-- 
alexandre lucchesi

*Perfection is achieved, not when there is nothing more to add, but when
there is nothing left to take away!*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20140902/d1f58cbf/attachment.html>


More information about the Beginners mailing list