aj_opinv
aj_opinv

Reputation: 71

Constraints on arguments to data constructor

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

Answers (2)

Silvio Mayolo
Silvio Mayolo

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

Auscyber
Auscyber

Reputation: 72

GADT's might help with this

I'm unsure if it will work like this. but with some typeclass arithmetic it might be possible

Upvotes: -2

Related Questions