Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 514
RussAbbott Avatar asked Nov 30 '16 03:11

RussAbbott


1 Answers

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.

like image 190
chi Avatar answered Nov 15 '22 22:11

chi