No title Revision 303561633331 (Tue May 17 2011 at 03:08) - Diff Link to this snippet: https://friendpaste.com/6CFralb4xTPxsiXlEzGkHe Embed: manni perldoc borland colorful default murphy trac fruity autumn bw emacs pastie friendly Show line numbers Wrap lines 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939421:09 ~/g/code/p6/t$ cat Tree/LLRB.pm6 class Tree::LLRB { class Node { has $.key is rw; has $.val is rw; has Node $.left is rw; has Node $.right is rw; has $.color is rw; method new($key, $val) { nextwith(self, :$key, :$val, :color<True>) } method colorFlip() { $.color = !$.color; $.left.color = !$.left.color if $.left; $.right.color = !$.right.color if $.right; } } sub isRed(Node $h) { $h and $h.color; } sub rotateLeft(Node $h) { my $x = $h.right; $h.right = $x.left; $x.left = $h; $x.color = $h.color; $h.color = True; return $x; } sub rotateRight(Node $h) { my $x = $h.left; $h.left = $x.right; $x.right = $h; $x.color = $h.color; $h.color = True; return $x; } has Node $!root; method insert($key, $val) { $!root = insert_at_node($!root, $key, $val); $!root.color = 'BLACK'; return self; } sub insert_at_node($h, $key, $val) { return Node.new($key, $val) unless $h; $h.colorFlip() if isRed($h.left) and isRed($h.right); given $key cmp $h.key { when 0 { $h.val = $val; } # Update in place when -1 { $h.left = insert_at_node($h.left, $key, $val); } when 1 { $h.right = insert_at_node($h.right, $key, $val); } } $h = rotateLeft($h) if isRed($h.right) and not isRed($h.left); $h = rotateRight($h) if isRed($h.left) and isRed($h.left.left); return $h; } method dump() { dump_node($!root, 0, 'ROOT'); } sub dump_node($h, $indent, $label) { print ' ' x $indent, "$label:".fmt('%6s'), ' '; if !$h { say ' ' x $indent, "LEAF"; } else { say ' ' x $indent, "$h.key => $h.val"; dump_node($h.left, $indent + 1, 'Left'); dump_node($h.right, $indent + 1, 'Right'); } }}21:09 ~/g/code/p6/t$ perl6 -e 'use Tree::LLRB; Tree::LLRB.new().insert(1, True).dump()'too many positional arguments: 2 passed, 1 expected in 'Node::new' at line 1 in 'Tree::LLRB::insert_at_node' at line 53:Tree/LLRB.pm6 in 'Tree::LLRB::insert' at line 47:Tree/LLRB.pm6 in main program body at line 1