Haskell,检查自定义数据类型是否满足某些限制

Haskell,检查自定义数据类型是否满足某些限制,haskell,functional-programming,Haskell,Functional Programming,这是我的ADT: type Color = String type Hight = Integer type Width = Integer type Des = String -- description data Shape = Shape Color [(Hight, Width)] Des deriving(Show) 我想定义一个名为“确认”的函数: confirm::Restriction->Shape->Bool 其中: false::Rest

这是我的ADT:

type Color = String
type Hight = Integer
type Width = Integer
type Des = String -- description 

data Shape = Shape Color [(Hight, Width)] Des
         deriving(Show)
我想定义一个名为“确认”的函数:

confirm::Restriction->Shape->Bool
其中:

false::Restriction -- the restriction fails


我需要帮助定义
限制
确认
更大
数据类型限制应该是
形状->布尔
。 然后您不需要
确认
,您可以使用
False
而不是
False

我已将
greater
重命名为
notTooBig
,因为这样数据正常时才是真的。我觉得这更有道理

notTooBig:: Shape -> Bool
notTooBig n (Shape _ dimensions _) = all smallenough dimensions where
  smallenough (h,w) = h <=n && w <= n

因此,让我们制定一个数据类型
限制
,以适合您:

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]
例如,你可以有
[color(=“red”),width(>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

展开另一个答案:

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

好吧你的问题是什么?你尝试过什么,又犯了什么错误?我只知道如何开始false。如何定义
限制
?当你发现自己试图重新定义基本概念,如true或false时,很可能你必须寻找不同的解决方案。@Gabriel Gonzalez家庭作业标签被正式删除。请不要将其添加到新问题中。家庭作业标签维基有更多信息。谢谢你的回答。但我必须定义false和confirm函数。
true :: Restrictions
true = []
false :: Restrictions
false = ColourR (const False)
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