Skip to content

Instantly share code, notes, and snippets.

@jonathanstowe
Created April 19, 2021 12:02
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 jonathanstowe/0441ed3539f72e9460fb7ce878053a5d to your computer and use it in GitHub Desktop.
Save jonathanstowe/0441ed3539f72e9460fb7ce878053a5d to your computer and use it in GitHub Desktop.
Named Tuple in Raku
class Tuple does Positional {
has $.a;
has $.b;
multi method AT-POS(0) {
$!a;
}
multi method AT-POS(1) {
$!b;
}
multi method COERCE(@i) {
self.new(a => @i[0], b => @i[1]);
}
}
sub namedtuple(Str $class, Str $a, Str $b --> Mu) {
my $type := Metamodel::ClassHOW.new_type(name => $class);
$type.^add_parent(Tuple);
$type.^add_method($a, method () { self.a });
$type.^add_method($b, method () { self.b });
$type.^compose;
$type;
}
constant Point = namedtuple('Point', 'x', 'y');
my $p = Point(1,2);
say $p.x;
say $p[0];
say $p.y;
say $p[1];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment