四叉树的模式匹配太多而无法记录?
想象一个四叉树定义如下:
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...
问题:我可以避免为叶子和四叉树的所有可能组合输入所有匹配项吗?< /em>
如果我的问题很奇怪,请耐心等待,但这是我的 Haskell 无缝学习的第二天!
Imagine a quadtree defined as follow:
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
The constructor allows you to create not well-formed quadtrees. bad1
should be simply C 255 and bad2
is not valid too because its bottom-right quadtree (for the same reason, it should be Q (C 0) (C 255) (C 244) (C 64)
.
So far so good. Checking its well-formness is simply a matter of checking its inner quadtrees recursively. The base case is when all inner quadtrees are leafs, whereby all colors shouldn't be all equals.
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...
Question: Can I avoid typing all matches for all possible combination of leafs and quadtrees?
Please be patient if my question is quite odd, but it's my second-day-Haskell-seamless-learing!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没关系...
编辑:或者更好:
编辑:请注意,绑定错误,应该是:NW NE SW SE!
Nevermind...
EDIT: or even better:
EDIT: note that the bindings are wrong, should be: NW NE SW SE!!!