简体   繁体   English

arguments 对数据构造函数的约束

[英]Constraints on arguments to data constructor

I am trying to define a data type for storing RGB values我正在尝试定义用于存储 RGB 值的数据类型

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?但是,由于参数始终位于[0-255]范围内,是否有办法将 arguments 限制为数据构造函数,以使值始终是有效颜色?

As the comments indicate, you can use Word8 , which has the desired range.如评论所示,您可以使用具有所需范围的Word8

import Data.Word(Word8)

data Color = Color Word8 Word8 Word8

Word8 implements Num so you can use regular integer constants with it. Word8实现了Num ,因此您可以使用常规的 integer 常量。

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 GADT 可能会对此有所帮助

I'm unsure if it will work like this.我不确定它是否会像这样工作。 but with some typeclass arithmetic it might be possible但是通过一些类型类算法,这可能是可能的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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