[Haskell-beginners] Data constraint?

Galaxy Being borgauf at gmail.com
Fri Jun 4 16:13:33 UTC 2021


Yes, I just discovered the HaskellWiki article on smart constructors! Will
give it a try.

On Fri, Jun 4, 2021, 11:01 AM Francesco Ariis <fa-ml at ariis.it> wrote:

> Il 03 giugno 2021 alle 17:40 Galaxy Being ha scritto:
> > If I have a type
> >
> > type WaterChem = CaHardness NaturalChem | Alkalinity NaturalChem
> >
> > and I want to have the values of CaHardness and Alkalinity constrained to
> > positive Int and between certain high and low values, I could do a
> newtype to
> > creater a NaturalChem number, thus never less than 0, but what is the
> best
> > practice to insure these values are between a certain range? Types in
> > Haskell can't go that far, can they? Reading this
>
> Mhhh you could create a smart constructor
>
>     data Prova = ProvConst Int      -- ProvConst does not get exported.
>
>     mkProva :: Int -> Prova         -- This does get exported.
>     mkProva i | i > 100 = 100  -- or error "…
>>
> In a «Parse, don’t validate» [1] fashion.
> If you need (as I suspect) to operate on those values, you will need
> to define a few typeclasses (`numbers` [2] is a good example from
> Hackage).
> Would that do?
> —F
>
> [1] https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/
> [2]
> https://hackage.haskell.org/package/numbers-3000.2.0.2/docs/Data-Number-Natural.html
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20210604/21efd2fa/attachment.html>


More information about the Beginners mailing list