1

想象一个四叉树定义如下:

data (Eq a, Show a) => QT a = C a | Q (QT a) (QT a) (QT a) (QT a)
  deriving (Eq, Show)

bad1 = Q u u u u where u = C 255
bad2 = Q (C 0) (C 255) (Q u u u u) (C 64) where u = C 255

构造函数允许您创建格式不正确的四叉树。bad1应该只是 C 255 并且bad2也无效,因为它的右下四叉树(出于同样的原因,它应该是Q (C 0) (C 255) (C 244) (C 64).

到现在为止还挺好。检查其良好形式只是递归检查其内部四叉树的问题。基本情况是当所有内部四叉树都是叶子时,所有颜色不应该都是相等的。

wellformed :: (Eq a, Show a) => QT a -> Bool
wellformed (Q (C c1) (C c2) (C c3) (C c4)) = any (/= c1) [c2, c3, c4]
wellformed (Q (C c1) (C c2) se (C c4))     = valid se
-- continue defining patters to match e.g Q C C C, C Q Q C, and so on...

问题我可以避免为叶子和四叉树的所有可能组合键入所有匹配项吗?

如果我的问题很奇怪,请耐心等待,但这是我第二天的 Haskell 无缝学习!

4

1 回答 1

4

没关系...

wellformed :: (Eq a, Show a) => QT a -> Bool
wellformed (C _) = True
wellformed (Q (C c1) (C c2) (C c3) (C c4)) = any (/= c1) [c2, c3, c4]
wellformed (Q nw ne se sw) = wellformed nw && wellformed ne
   && wellformed se && wellformed sw

编辑:甚至更好:

wellformed :: (Eq a, Show a) => QT a -> Bool
wellformed (C _) = True
wellformed (Q (C c1) (C c2) (C c3) (C c4)) = any (/= c1) [c2, c3, c4]
wellformed (Q nw ne se sw) = all wellformed [nw, ne, se, sw]

编辑:注意绑定是错误的,应该是:NW NE SW SE!!!

于 2011-02-04T05:20:45.173 回答