Tree datastructures: Difference between revisions
Content added Content deleted
SqrtNegInf (talk | contribs) m (→{{header|Perl}}: tweak) |
SqrtNegInf (talk | contribs) (→{{header|Perl}}: native format / JSON) |
||
Line 164: | Line 164: | ||
use warnings; |
use warnings; |
||
use feature 'say'; |
use feature 'say'; |
||
use JSON; |
|||
use Data::Printer; |
|||
my $trees = <<~END; |
my $trees = <<~END; |
||
Line 187: | Line 189: | ||
say my $indent = nested_to_indent $trees; |
say my $indent = nested_to_indent $trees; |
||
my $nest = indent_to_nested $indent; |
|||
use Test::More; |
use Test::More; |
||
is($trees, $nest, 'Round-trip |
is($trees, $nest, 'Round-trip'); |
||
done_testing(); |
done_testing(); |
||
# Import outline paragraph into native data structure |
|||
sub import { |
|||
my($trees) = @_; |
|||
my $level = ' '; |
|||
my $forest; |
|||
my $last = -999; |
|||
for my $branch (split /\n/, $trees) { |
|||
$branch =~ m/(($level*))*/; |
|||
my $this = $1 ? length($1)/length($level) : 0; |
|||
$forest .= do { |
|||
if ($this gt $last) { '[' . trim_and_quote($branch) } |
|||
elsif ($this lt $last) { ']'x($last-$this).',' . trim_and_quote($branch) } |
|||
else { trim_and_quote($branch) } |
|||
}; |
|||
$last = $this; |
|||
} |
|||
sub trim_and_quote { shift =~ s/^\s*(.*\S)\s*$/"$1",/r } |
|||
eval $forest . ']' x (1+$last); |
|||
} |
|||
my $forest = import $trees; |
|||
say "Native data structure:\n" . np $forest; |
|||
say "\nJSON:\n" . encode_json($forest);</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre>RosettaCode |
||
1 encourages |
1 encourages |
||
2 code |
2 code |
||
Line 202: | Line 230: | ||
2 trolling |
2 trolling |
||
2 emphasising execution speed |
2 emphasising execution speed |
||
code-golf.io |
|||
1 encourages |
1 encourages |
||
2 golfing |
2 golfing |
||
Line 208: | Line 236: | ||
2 comparison |
2 comparison |
||
ok 1 - Round-trip |
ok 1 - Round-trip |
||
1..1 |
1..1 |
||
</pre> |
|||
Native data structure: |
|||
\ [ |
|||
[0] "RosettaCode", |
|||
[1] [ |
|||
[0] "encourages", |
|||
[1] [ |
|||
[0] "code", |
|||
[1] [ |
|||
[0] "diversity", |
|||
[1] "comparison" |
|||
] |
|||
], |
|||
[2] "discourages", |
|||
[3] [ |
|||
[0] "golfing", |
|||
[1] "trolling", |
|||
[2] "emphasising execution speed" |
|||
] |
|||
], |
|||
[2] "code-golf.io", |
|||
[3] [ |
|||
[0] "encourages", |
|||
[1] [ |
|||
[0] "golfing" |
|||
], |
|||
[2] "discourages", |
|||
[3] [ |
|||
[0] "comparison" |
|||
] |
|||
] |
|||
] |
|||
JSON: |
|||
["RosettaCode",["encourages",["code",["diversity","comparison"]],"discourages",["golfing","trolling","emphasising execution speed"]],"code-golf.io",["encourages",["golfing"],"discourages",["comparison"]]]</pre> |
|||
=={{header|Perl 6}}== |
=={{header|Perl 6}}== |