简体   繁体   中英

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?

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

GADT's might help with this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM