-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
- Loading branch information
Showing
2 changed files
with
71 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
module main | ||
|
||
import arrays | ||
|
||
pub struct Tree { | ||
pub: | ||
// Type of structural node, `value` should be empty | ||
type string | ||
// Content of data node, `type` should be empty | ||
value string | ||
pub mut: | ||
// Child nodes | ||
kids []&Tree | ||
} | ||
|
||
@[params] | ||
struct TreeCloneParams { | ||
kids []&Tree | ||
} | ||
|
||
// Makes new derived node with different kids id defined. | ||
pub fn (tree Tree) clone(p TreeCloneParams) &Tree { | ||
return &Tree{ | ||
type: tree.type | ||
value: tree.value | ||
kids: p.kids | ||
} | ||
} | ||
|
||
// Collection of hask tools for processing tree. | ||
pub type TreeBelt = map[string]fn (input &Tree, belt TreeBelt) []&Tree | ||
|
||
// Hask tool for processing node. | ||
pub type TreeHack = fn (input &Tree, belt TreeBelt) []&Tree | ||
|
||
pub type TreeContext = map[string]string | ||
|
||
@[params] | ||
struct TreeHackParams { | ||
belt TreeBelt | ||
context ?TreeContext | ||
} | ||
|
||
// Transform tree through context with transformers | ||
pub fn (tree Tree) hack(p TreeHackParams) []&Tree { | ||
return arrays.concat(arrays.flatten(tree.kids.map(it.hack_self(p)))) | ||
} | ||
|
||
pub fn (tree Tree) hack_self(p TreeHackParams) []&Tree { | ||
mut handle := fn [tree] (input &Tree, belt TreeBelt) []&Tree { | ||
return [ | ||
input.clone(kids: input.hack(belt: belt)), | ||
] | ||
} | ||
|
||
if action := p.belt[tree.type] { | ||
handle = action | ||
} | ||
|
||
return handle(tree, p.belt) | ||
} | ||
|
||
fn test_main() { | ||
t := Tree{} | ||
r := t.hack_self(belt: TreeBelt(map[string]fn (&Tree, TreeBelt) []&Tree{})) | ||
assert r[0].type == '' | ||
assert r[0].value == '' | ||
assert r[0].kids.len == 0 | ||
} |