简体   繁体   中英

What sort of iterations does GHC do while compiling patterns?

I just wrote a function for making a move in Tic-Tac-Toe. I wanted to push pattern matching. So I wrote 9 makeAMove clauses. Each has a Tic-Tac-Toe board with a different space designated by an Empty symbol. It looks something like this.

makeAMove [[E,   m12, m13],
           [m21, m22, m23],
           [m31, m32, m33]] X 1 1 = ...

This clause would put an X in the upper left corner of the board. X, O, and E are defined as Marks.

data Mark = X |  O | E deriving (Eq, Show)

When I load the file I get this warning message.

warning:
    Pattern match checker exceeded (2000000) iterations in
    an equation for ‘mov1’. (Use -fmax-pmcheck-iterations=n
    to set the maximun number of iterations to n)

My question is one of curiosity. What sort of iterations is the pattern matcher doing? And why are so many required?

When I limit the number of clauses to, say, 5 and put the rest in another function that is linked to by a default case, there is no problem.

Here's a MCVE:

{-# OPTIONS -Wall #-}
data T = O | A | B | C | D | E

f :: T -> T -> T -> T -> T -> T -> T -> T -> T -> ()
f O _ _ _ _ _ _ _ _ = ()
f _ O _ _ _ _ _ _ _ = ()
f _ _ O _ _ _ _ _ _ = ()
f _ _ _ O _ _ _ _ _ = ()
f _ _ _ _ O _ _ _ _ = ()
f _ _ _ _ _ O _ _ _ = ()
f _ _ _ _ _ _ O _ _ = ()
f _ _ _ _ _ _ _ O _ = ()
f _ _ _ _ _ _ _ _ O = ()

Result:

ExhaustivePattern3.hs:5:5: warning:
    Pattern match checker exceeded (2000000) iterations in
    an equation for ‘f’. (Use -fmax-pmcheck-iterations=n
    to set the maximun number of iterations to n)

I guess the checker is trying to generate the counterexamples too eagerly: there are many unmatched patterns, exponentially growing with the number of arguments.

Indeed, after the first match the unmatched cases are

A _ _ _ _ _ _ _ _
B _ _ _ _ _ _ _ _
...
E _ _ _ _ _ _ _ _

Then after the second one, this expands to:

A A _ _ _ _ _ _ _
A ...
A E _ _ _ _ _ _ _
B A _ _ _ _ _ _ _
B ...
B E _ _ _ _ _ _ _
...
E A _ _ _ _ _ _ _
E ...
E E _ _ _ _ _ _ _

And so on. This grows exponentially.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM