Skip to content

Instantly share code, notes, and snippets.

@moritz
Created October 5, 2011 20:43
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save moritz/1265646 to your computer and use it in GitHub Desktop.
mostly correct and complete &min implementation
sub my-min(*@values, :&by = &infix:<cmp>) {
my Mu $min;
if &by.arity == 0|1 {
my &transform := &by.arity == 0 ?? -> $x { by() } !! &by;
my $min-return;
$min = transform(@values[0]);
for @values {
# FIRST next;
my $current := transform($_);
if $current cmp $min < 0 {
$min = $current;
$min-return = $_;
}
}
@values ?? $min-return !! -Inf;
} else {
my &cmp := &by.arity == 2 ?? &by !! { $^a cmp $^b };
my Bool $is-initialized = False;
for @values {
if $is-initialized {
$min = $_ if cmp($_, $min) < 0;
} else {
if .defined {
$min = $_;
$is-initialized = True;
}
}
}
$is-initialized ?? $min !! -Inf;
}
}
say my-min(Any, Any);
say my-min();
say my-min(-3, 5, -8, 9);
say my-min(Any, -3, 5, -8, 9);
say my-min('ab', 'foo', 'bar', 'aa');
say my-min(1..20, :by(&rand));
say my-min(-3, 5, -8, 9, :by(&prefix:<->));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment