Reputation: 71
I am trying to define a data type for storing RGB values
data Color = RGB Int Int Int
black = RGB 0 0 0
However since parameters always lie in range [0-255]
, is there a way to constrain arguments to data constructor such that value is always a valid color?
Upvotes: 1
Views: 149
Reputation: 70267
As the comments indicate, you can use Word8
, which has the desired range.
import Data.Word(Word8)
data Color = Color Word8 Word8 Word8
Word8
implements Num
so you can use regular integer constants with it.
The more general solution to the problem "I have a constraint that can't be expressed with types" is to hide your constructor and make a checked interface. In your case, that would manifest as
data Color = Color Int Int Int -- Don't export the constructor
color :: Int -> Int -> Int -> Maybe Color
color r g b
| r < 256 && g < 256 && b < 256 = Just (Color r g b)
| otherwise = Nothing
Upvotes: 4
Reputation: 72
I'm unsure if it will work like this. but with some typeclass arithmetic it might be possible
Upvotes: -2