Skip to content

Instantly share code, notes, and snippets.

@ab5tract
Last active August 29, 2015 14:11
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 ab5tract/e73592ae73516477a522 to your computer and use it in GitHub Desktop.
Save ab5tract/e73592ae73516477a522 to your computer and use it in GitHub Desktop.
Perl 6 "Coercers and Composers" Followup
class ForYou {
has $.contents;
has $.recipient;
method give {
example_say "Hey " ~ $!recipient ~ "! A " ~ $!contents;
}
};
class Present {
has $.contents;
has $.recipient is rw;
method ForYou {
$!recipient ?? ForYou.new( contents => $!contents ~ ", just for you!", :$!recipient )
!! die "Can't have a Present become a ForYou without a recipient";
}
method give {
if $!recipient {
self.ForYou.give;
} else {
example_say "Hey, we haven't met before but I've got a " ~ $!contents ~ ", if you're keen.";
}
}
};
advent_say 'creating object of type Present';
my $present = Present.new( contents => "new Perl" );
example_say $present.perl;
advent_say 'giving this $present to whomever';
$present.give;
advent_say 'attempted coercion through .ForYou syntax (but missing something)';
try $present.ForYou;
example_say $!.perl;
advent_say 'giving this $present to that $recipient';
$present.recipient = '$*WORLD';
example_say $present.perl;
advent_say 'object introspection after coercing through .ForYou syntax';
example_say $present.ForYou.perl;
advent_say 'giving this $present after coercing through ForYou() syntax';
ForYou( $present ).give;
# -Ofun presentation subs
sub advent_say( Str $to_say, :$text-columns = 80, :$flakes = 6 ) {
my $prefix = [~] [ '❆ ','❄ ', '❅ ' ].roll($flakes);
my $suffix = [~] [ '❆ ','❄ ', '❅ ' ].roll($flakes);
my $to_out = $to_say ~ '' xx ($text-columns - $flakes*2 - $to_say.comb);
say $prefix ~ $to_out ~ $suffix;
}
sub example_say( Str $to_say ) {
say "\n\t" ~ $to_say ~ "\n";
}
❆ ❆ ❅ ❄ ❄ ❆ creating object of type Present ❆ ❅ ❆ ❄ ❅ ❄
Present.new(contents => "new Perl", recipient => Any)
❅ ❅ ❅ ❄ ❆ ❄ giving this $present to whomever ❅ ❆ ❆ ❆ ❆ ❅
Hey, we haven't met before but I've got a new Perl, if you're keen.
❅ ❄ ❄ ❆ ❆ ❅ attempted coercion through .ForYou syntax (but missing something) ❅ ❆ ❆ ❄ ❆ ❄
X::AdHoc.new(payload => "Can't have a Present become a ForYou without a recipient")
❆ ❅ ❆ ❅ ❅ ❅ giving this $present to that $recipient ❄ ❄ ❅ ❅ ❆ ❅
Present.new(contents => "new Perl", recipient => "\$*WORLD")
❄ ❅ ❅ ❅ ❆ ❆ object introspection after coercing through .ForYou syntax ❄ ❅ ❅ ❅ ❄ ❅
ForYou.new(contents => "new Perl, just for you!", recipient => "\$*WORLD")
❆ ❄ ❆ ❆ ❅ ❄ giving this $present after coercing through ForYou() syntax ❅ ❅ ❅ ❄ ❅ ❄
Hey $*WORLD! A new Perl, just for you!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment