1

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?

1
  • 6
    Well, you can just use Word8 instead of Int. Commented Feb 25, 2021 at 4:26

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

see also: Smart constructors (that's what the second solution mentioned in this answer is usually called)
These days there's an even smarter/prettier way to make smart constructors: use an explicitly bi-directional pattern synonym downloads.haskell.org/~ghc/8.10.4/docs/html/users_guide/…, call it Color (upper case), call the constructor in the datatype something else, and don't export it, as the answer says.
-2

GADT's might help with this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.