问题
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!
回答1:
Nevermind...
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
EDIT: or even better:
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]
EDIT: note that the bindings are wrong, should be: NW NE SW SE!!!
来源:https://stackoverflow.com/questions/4894798/too-many-pattern-matches-to-write-down-for-quadtrees