Tree traversal: Difference between revisions
→JS ES6: Updated primitives, tidied
(→JS ES6: Updated primitives, tidied) |
|||
Line 5,904:
{{Trans|Python}}
<lang JavaScript>(() => {
const foldTree = f =>▼
// value obtained by a depth-first fold.▼
tree => {▼
const go = x => f(x.root)(▼
x.nest.map(go)▼
);▼
return go(tree);▼
};▼
// preorder :: a -> [[a]] -> [a]
const preorder = x =>
xs => [x, ...
// inorder :: a -> [[a]] -> [a]
const inorder = x =>
xs =>
[...xs[0], x, ...
) : [x];
// postorder :: a -> [[a]] -> [a]
const postorder = x =>
xs => [...
// levelOrder :: Tree a -> [a]
const levelOrder = tree =>
[tree]▼
)▼
)▼
);▼
// ------------------------TEST------------------------
const main = () => {
const tree = Node(1)([
Line 5,961 ⟶ 5,946:
// task: 'Visualize a tree'
console.log([
].join(
[preorder, inorder, postorder]
.forEach(f => console.log(
tree▼
)▼
)
));
console.log(
);
};
// -----------------
// Node :: a -> [Tree a] -> Tree a
Line 5,993 ⟶ 5,976:
// more child trees.
xs => ({
type:
root: v,
nest: xs || []
});
0 < xs.length ? (▼
//
const
▲ // value obtained by a depth-first fold.
};▼
// levels :: Tree a ->
const levels = tree =>
// A list of lists, grouping the
// values of each
...node.nest.reduceRight(go, t)
};
// --------------------- GENERIC ---------------------
// justifyRight :: Int -> Char -> String -> String
Line 6,025 ⟶ 6,021:
// The string s, preceded by enough padding (with
// the character c) to reach the string length n.
c => s =>
s.padStart(n, c)
) :
▲ // root :: Tree a -> a
▲ }
▲ };
// MAIN ---
|