# Function argument with tree type

I liked to define a function argument type representing a tree with only nodes: 0,1. Every subtree is defined as a list like this: {node,{subtree1},{subtree2},...} The definition is recursive. The most basic structures are the root only trees: {0},{1}.

• The build-in (experimental) function Tree[ ] is not useful for your purpose? Commented Jul 19 at 6:02
• It's too general for my purposes. Commented Jul 19 at 7:49

Here is a possible simple implementation:

nodeQ[node_] := MatchQ[node, 0 | 1];
treeQ[tree_] := MatchQ[tree, {_?nodeQ, ___?treeQ}];

f[tree_?treeQ] := tree
f[___] := $Failed f[{0}] (* {0} *) f[{3}] (*$Failed *)

f[{0, {1}}]
(* {0, {1}} *)

f[{0, 1, 2}]
(* \$Failed *)

f[{0, {1}, {0, {1, {0, {1}}}}}]
(* {0, {1}, {0, {1, {0, {1}}}}} *)


If you really want to have a single pattern, look at How to define a recursive pattern?.

• I guessed there is no way to build a pattern. So the function is the best solution. I made a function that is longest than yours. But your solution can be improved this way: treeQ[tree_] := MatchQ[tree, {0 | 1, ___?treeQ}] Commented Jul 19 at 17:15
• @GiovanniRusso, I have deliberately separated nodeQ and treeQ, but you can merge them in one, sure. As for the single pattern: Search for recursive patterns. Commented Jul 19 at 17:23