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

Julian Birch julian.birch at gmail.com
Tue Sep 2 22:02:48 UTC 2014


Also, if you want your mind blown, check out Idris.

On Tuesday, September 2, 2014, Alexandre Lucchesi <
alexandrelucchesi at gmail.com> wrote:

> 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
> <javascript:_e(%7B%7D,'cvml','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
>> <javascript:_e(%7B%7D,'cvml','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!*
>


-- 
Sent from an iPhone, please excuse brevity and typos.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20140902/bfae26be/attachment.html>


More information about the Beginners mailing list