Created
April 19, 2021 12:02
-
-
Save jonathanstowe/0441ed3539f72e9460fb7ce878053a5d to your computer and use it in GitHub Desktop.
Named Tuple in Raku
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
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