Created
December 5, 2025 12:06
-
-
Save 0racle/0757b204583aa54db497b02a4114ce50 to your computer and use it in GitHub Desktop.
Raku Translation of Python's Bisect module
This file contains hidden or 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
| my %exports; | |
| module Bisect { | |
| #|Insert $x in @a, and keep it sorted assuming @a is sorted. | |
| our sub insort-right(@a, $x, :$lo is copy = 0, :$hi, :$key) { | |
| $lo = bisect-right(@a, $key($x), :$lo, :$hi, :$key); | |
| @a.splice($lo, 0, $x); | |
| } | |
| #|Return the index where to insert $x in @a, assuming @a is sorted. | |
| our sub bisect-right( | |
| @a, | |
| Any:D $x, | |
| UInt :$lo is copy = 0, | |
| UInt :$hi is copy = @a.elems, | |
| Callable :$key={$_} | |
| ) { | |
| while $lo < $hi { | |
| my $mid = ($lo + $hi) div 2; | |
| if $x < $key(@a[$mid]) { | |
| $hi = $mid | |
| } | |
| else { | |
| $lo = $mid + 1 | |
| } | |
| } | |
| return $lo | |
| } | |
| #|Insert $x in @a, and keep it sorted assuming @a is sorted. | |
| our sub insort-left(@a, $x, :$lo is copy = 0, :$hi, :$key) { | |
| $lo = bisect-left(@a, $key($x), :$lo, :$hi, :$key); | |
| @a.splice($lo, 0, $x); | |
| } | |
| #|Return the index where to insert $x in list @a, assuming @a is sorted. | |
| our sub bisect-left( | |
| @a, | |
| Any:D $x, | |
| UInt :$lo is copy = 0, | |
| UInt :$hi is copy = @a.elems, | |
| Callable :$key={$_} | |
| ) { | |
| while $lo < $hi { | |
| my $mid = ($lo + $hi) div 2; | |
| if $key(@a[$mid]) < $x { | |
| $lo = $mid + 1 | |
| } | |
| else { | |
| $hi = $mid | |
| } | |
| } | |
| return $lo | |
| } | |
| our &bisect = &bisect-right; | |
| our &insort = &insort-right; | |
| %exports = MY::.grep(*.key.starts-with: '&') | |
| } | |
| multi sub EXPORT(*@names) { | |
| my %imports; | |
| for @names -> $name { | |
| unless %exports{"&$name"}:exists { | |
| die("Unknown name for export: '$name'"); | |
| } | |
| %imports{"&$name"} := %exports{"&$name"} | |
| } | |
| return %imports | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment