forked from nushell/nu_scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.nu
54 lines (35 loc) · 1.29 KB
/
tree.nu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# tree.nu: module for working with trees
source typeof.nu # Requires Nushell version 0.88 or later
# A tree is a recursive data structure. In Nu, we take the view that any single atomic value
# is a leaf. E.g. int, float, string, bool, etc.
# Any structured data is some kind of a tree. E.g. list, record or table.
# Applies closure to atomic data.
def visit-scalar [act: closure] {
let data = $in
do $act $data
}
# Visit every element of list and apply closure
def visit-list [act: closure] {
let l = $in
$l |each {|x| $x | visit $act }
}
# Apply closure to every column and value of record in input. Does a visit on
# each key and then on each value.
def visit-record [cl: closure] {
items {|k, v| $k | visit $cl; $v | visit $cl }
}
# Applies closure to every row in table passed to input. Defers to visit-record
# for each row.
def visit-table [act: closure] {
each {|r| $r | visit-record $act }
}
# Applies closure to every node in tree passed to input recursively.
def visit [act: closure] {
let stream = $in
match ($stream | typeof) {
'list' => { do $act 'list'; $stream | visit-list $act },
'record' => { do $act 'record'; $stream | visit-record $act },
'table' => { do $act 'table'; $stream | visit-table $act },
_ => { $stream | visit-scalar $act }
}
}