Luke Palmer wrote:
sub a_pure_func(Num $n) returns Num {
class is Num {
method FETCH { $n * $n } }.new
}
Yes? No?
Not quite.
> sub a_pure_func(Num $n) returns Num {
> class is Num {
> has Num $cache;
> method FETCH { $cache //= $n * $n } } }
Still not quite.
You don't want a C<FETCH> method (which won't be called unless the
object somehow becomes the implementation of a tied variable).
What you want are conversion-to-(num|str|bool) methods:
sub a_pure_func(Num $n) returns Num {
class is Num {
has Num $cache;
sub value { $n * $n }
method operator:+ ($self:) { +($cache //= value ) }
method operator:~ ($self:) { ~($cache //= value ) }
method operator:? ($self:) { ?($cache //= value ) }
}.new
}
> Wow, I've never seen such a compact implementation of such a thing. I
> love you, Perl 6
:-)
Damian