[Haskell-beginners] Data constraint?

Francesco Ariis fa-ml at ariis.it
Fri Jun 4 15:58:51 UTC 2021


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


More information about the Beginners mailing list