Is there a way to conditionally take control the flow during a depth-first scan against a TreeGraph?

I have a tree graph whose nodes are constructed as object, and there's a method isTrue[para_] for each node.

isValid[desc] = "Check whether input is valid";
isValid[isTrue, para_] := Module[{result},
    result = SyntaxQ[para];

isNumber[desc] = "Check whether input is a number";
isNumber[isTrue, para_] := Module[{result},
    result = NumberQ[ToExpression[para]];

isInteger[desc] = "Check whether input is an integer";
isInteger[isTrue, para_] := Module[{result},
    result = IntegerQ[ToExpression[para]];

isFraction[desc] = "Check whether input is a fraction";
isFraction[isTrue, para_] := Module[{result},
    result = !IntegerQ[ToExpression[para]];

tree = 
  TreeGraph[{isValid, isNumber, isInteger, isFraction}, 
    {isValid -> isNumber, isNumber -> isInteger, isNumber -> isFraction},

Here is the tree image of the code, The root is isValid.

The structure of tree

If my input is "3.5", I expect the depth-scan flow should be isValid -> isNumber -> isFraction because the isInteger gives False.

I tried Abort[] like (as well as Return[]):

DepthFirstScan[tree, isValid, 
 "DiscoverVertex" -> (If[#[isTrue, "3.5"], Print[#], Abort[]]&)];

But this broke the whole scan flow. What I want is: when the node gives False, it and its child-nodes should be skipped, but the scan should continue scanning the remaining nodes.

  • $\begingroup$ Some advice on coding. isValid can be reduced to isValid[isTrue, para_] := SyntaxQ[para]. Similar reductions can be made to your other functions. $\endgroup$ – m_goldberg Nov 4 '13 at 12:45
  • $\begingroup$ @m_goldberg thanks for your advice. $\endgroup$ – Michael Nov 4 '13 at 13:11

DepthFirstScan as well as BreadthFirstScan has no such functionality. However, you can construct a temporary graph without unwanted edges

n = 8;
g = GridGraph[{n, n}, DirectedEdges -> True, 
  VertexStyle -> Thread[Range[n^2] -> RandomChoice[{3, 1} -> {White, Black}, n^2]]]

enter image description here

Here invalid vertices marked by black. Let's delete all corresponding edges

g2 = EdgeDelete[g, DirectedEdge[_, n_] /; PropertyValue[{g, n}, VertexStyle] == Black];

visited = Reap[DepthFirstScan[g2, 1, {"DiscoverVertex" -> (Sow[#] &)}]][[2, 1]];

HighlightGraph[g, visited]

enter image description here

| improve this answer | |
  • $\begingroup$ thanks a lot. You pointed me a correct way to do this. $\endgroup$ – Michael Nov 5 '13 at 6:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.