Search code examples
haskelltypesfunctional-programmingtype-theoryhindley-milner

Limit a number to a range (Haskell)


I am exposing a function which takes two parameters, one is a minimum bound and the other is a maximum bound. How can I ensure, using types, that for example the minimum bound is not greater than the maximum bound?

I want to avoid creating a smart constructor and returning a Maybe because it would make the whole usage more cumbersome.

Thank you


Solution

  • This doesn't exactly answer your question, but one approach that sometimes works is to change your interpretation of your type. For example, instead of

    data Range = {lo :: Integer, hi :: Integer}
    

    you could use

    data Range = {lo :: Integer, size :: Natural}
    

    This way, there's no way to represent an invalid range.