这是我的ADT:
type Color = String
type Hight = Integer
type Width = Integer
type Des = String -- description
data Shape = Shape Color [(Hight, Width)] Des
deriving(Show)
我想定义一个名为confirm
的函数:
confirm::Restriction->Shape->Bool
其中:
false::Restriction -- the restriction fails
和
greater::Integer->Restriction --height or width is greater than given number
我需要帮助定义Restriction
,confirm
,false
和greater
答案 0 :(得分:2)
数据类型限制应 Shape -> Bool
。
您不需要confirm
,并且可以使用False
代替false
。
我已将greater
重命名为notTooBig
,因为当数据正常时它就是真的。我觉得这更有意义。
notTooBig:: Shape -> Bool
notTooBig n (Shape _ dimensions _) = all smallenough dimensions where
smallenough (h,w) = h <=n && w <= n
_
表示忽略此位 - 我们不需要颜色或说明。
编辑:对你来说似乎非常重要
confirm::Restriction->Shape->Bool
和
false::Restriction -- the restriction fails
所以让我们创建一个适合您的数据类型Restriction
:
data ARestriction = ColourR (Colour -> Bool) -- (sorry I can't resist using British spelling)
| HeightR (Height -> Bool) -- (Hight is surely a typo)
| WidthR (Width -> Bool)
| DesR (Des -> Bool)
type Restrictions = [ARestriction]
所以,例如,你可以[ColourR (=="red"), WidthR (>7)]
只允许比7更宽的红色事物。
confirm1 :: ARestriction -> Shape -> Bool
confirm1 (ColourR check) (Shape c ds d) = check c
confirm1 (HeightR check) (Shape c ds d) = all check $ map fst ds
confirm1 (WidthR check) (Shape c ds d) = all check $ map snd ds
confirm1 (DesR check) (Shape c ds d) = check d
confirm :: Restrictions -> Shape -> Bool
confirm rs s = all (flip confirm1 s) rs
无论如何,我们可以这样使用:
confirm [ColourR (=="red"), WidthR (>7)] (Shape "red" [(2,3),(3,4)] "square")
为您提供True
。
您还想定义false
,但我们先试试true
:
true :: Restrictions
true = []
这是有效的,因为列表中的所有限制都得到了满足。
您还可以定义
false :: Restrictions
false = ColourR (const False)
用于检查形状的颜色,但const
会告诉您False
。
答案 1 :(得分:1)
扩展另一个答案:
type Restriction = (Shape -> Bool)
false :: Restriction
false = const False
greater :: Integer -> Restriction
greater r (Shape _ dims _) = any (\(h,w) -> h > r || w > r) dims
confirm :: Restriction -> Shape -> Bool
confirm = id