Skip to content

Instantly share code, notes, and snippets.

@treyharris
Created May 4, 2017 16:43
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 treyharris/a7001bf7f52cf64a6ade89e35a23a047 to your computer and use it in GitHub Desktop.
Save treyharris/a7001bf7f52cf64a6ade89e35a23a047 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl6
# From Language/container.pod6:
sub lucky(::T $type) {
my T $c-value; # closure variable
return Proxy.new(
FETCH => method () { $c-value },
STORE => method (T $new-value) {
X::OutOfRange.new(what => 'number', got => '13', range => '-∞..12, 14..∞').throw
if $new-value == 13;
$c-value = $new-value;
}
);
}
my Int $a := lucky(Int);
say $a = 12; # OUTPUT: «12␤»
say $a = 'FOO'; # X::TypeCheck::Binding
say $a = 13; # X::OutOfRange
CATCH { default { say .^name, ': ', .Str; say "Attempting to resume..."; if ! (.can('resumable') && .resumable) { .rethrow }; say "Resuming..."; .resume } };
# 12
# X::TypeCheck::Binding::Parameter: Type check failed in binding to parameter '$new-value'; expected Int but got Str ("FOO")
# Attempting to resume...
# This representation (VMException) does not support associative access (for type BOOTException)
# in block at /tmp/doctest.p6 line 19
# in method <anon> at /tmp/doctest.p6 line 7
# in block <unit> at /tmp/doctest.p6 line 17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment