Skip to content

Instantly share code, notes, and snippets.

@moritz
Created April 13, 2012 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moritz/2379772 to your computer and use it in GitHub Desktop.
Save moritz/2379772 to your computer and use it in GitHub Desktop.
Auto-generated dependent comparison operators
use AutoGen;
class A {
has $.x;
multi infix:<cmp>(A $a, A $b) is autogen {
$a.x cmp $b.x;
}
}
module AutoGen {
my %names =
cmp => <before after>,
leg => <gt lt ge le eq>,
'<=>' => ('>', '<', '>=', '<=', '==')
;
multi trait_mod:<is>(&routine, :$autogen!) is export {
my @ops =
sub ($a, $b) { routine($a, $b) == Increase },
sub ($a, $b) { routine($a, $b) == Decrease },
sub ($a, $b) { routine($a, $b) != Decrease },
sub ($a, $b) { routine($a, $b) != Increase },
sub ($a, $b) { routine($a, $b) == Same },
;
my $shortname = &routine.name.substr(7, *-1);
for %names{$shortname}.list Z @ops -> $n, $o {
my role named { has $.name };
$o does named("infix:<$n>");
for &routine.signature.params.kv -> $i, $p {
nqp::bindattr(nqp::p6decont($o.signature.params[$i]),
Parameter, '$!nominal_type', $p.type);
}
trait_mod:<is>(:export, $o);
}
}
}
$ ./perl6 -e 'use A; say A.new(x => 5) before A.new(x => 7)'
True
$ ./perl6 -e 'use A; say "a" before "b"'
===SORRY!===
CHECK FAILED:
Calling 'infix:<before>' will never work with argument types (str, str) (line 1)
Expected: :(A $a, A $b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment