Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit a Int field to a range of values?

Tags:

haskell

In my Data

data User = User { uRank :: Int, uProgress :: Int }

I want to limit uRank to a list of values [-1, 1, 3], for example.

How do I do this?

like image 517
McBear Holden Avatar asked Jan 19 '17 13:01

McBear Holden


1 Answers

Defining a small sum type is the best answer for this specific question. You can also use newtype with smart constructors to achieve this effect.

newtype Rank = UnsafeMkRank { unRank :: Int }

mkRank :: Int -> Maybe Rank
mkRank i 
    | i `elem` [-1, 1, 3] = Just (UnsafeMkRank i)
    | otherwise = Nothing

Now, provided you only use the safe mkRank constructor, you can assume that your Rank values have the Int values you want.

like image 78
ephrion Avatar answered Oct 06 '22 15:10

ephrion