1

这是我的 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,confirmfalsegreater

4

2 回答 2

2

数据类型限制应该 Shape -> Bool。然后你不需要confirm,你可以使用False代替false

我已重命名为greaternotTooBig因为当数据正常时它是真的。我觉得这更有意义。

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

于 2012-10-22T16:16:50.487 回答
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
于 2012-10-22T17:09:22.643 回答