Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
Some advice on coding. isValid can be reduced to isValid[isTrue, para_] := SyntaxQ[para]. Similar reductions can be made to your other functions. – m_goldberg Nov 4 '13 at 12:45
@m_goldberg thanks for your advice. – Michael Nov 4 '13 at 13:11
up vote 2 down vote accepted

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

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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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