I am modelling binary trees in Wolfram Language by writing them as three-element lists, like so: binTree = {nodeVal, leftChild, rightChild}
.
It does not yet matter what kind of structure nodeVal
itself has, but let us assume, for the sake of this problem, that the structure is a list of two integers: nodeValPattern = {_Integer, _Integer}
.
Furthermore, leftChild
and rightChild
can be either {}
or have internal nodes of the same shape as binTree
itself.
I would like to have a pattern guard for the structure of binTree
. The naive attempt does not work:
nodeValPattern = {_Integer, _Integer};
binTreePattern = {nodeValPattern, ({} | binTreePattern), ({} | binTreePattern)};
binTree = {
{{1, 2}, {{2, 3}, {}, {}}, {}},
{{3, 4}, {}, {{4, 5}, {}, {}}},
{}
};
MatchQ[binTree, binTreePattern]
I get the following error:
$RecursionLimit::reclim: Recursion depth of 1024 exceeded. >>
Can you please help?