sub fib { my $nth = shift; return $nth if $nth <= 1; return fib( $nth - 1 ) + fib( $nth - 2 ); } #### sub fib { croak("…") if @_ != 1; my $nth = $_[0]; croak("…") if not defined $nth; croak("…") if $nth !~ /^+?\d+$/a; return $nth if $nth <= 1; return fib( $nth - 1 ) + fib( $nth - 2 ); } #### sub fib(UInt $nth) { return $nth if $nth <= 1; return fib( $nth - 1 ) + fib( $nth - 2 ) } #### class Point attr_accessor :x attr_accessor :y def initialize x, y @x = x @y = y end def inverted return Point.new @y, @x end end #### class Point { public $x, $y; public function __construct ($x, $y) { $this->x = $x; $this->y = $y; } public function inverted() { return new Point( $this->y, $this->x ); } } #### class Point: def __init__(self, x, y): self.x = x self.y = y def inverted(self): return Point(self.y,self.x) #### package Point; use Carp 'croak'; sub new { croak('…') unless @_ == 3; my ( $class, $x, $y ) = @_; return bless { x => $x, y => $y } => $class; } sub x { croak('…') unless @_ == 1 || @_ == 2; my $self = shift if ( @_ ) { $self->{x} = shift; } return $self->{x}; } sub y { croak('…') unless @_ == 1 || @_ == 2; my $self = shift if ( @_ ) { $self->{y} = shift; } return $self->{y}; } sub inverted { croak('…') unless @_ == 1; my $self = shift; return Point->new( $self->y, $self->x ); } 1; #### class Point { has Num ($x, $y); method inverted () { return Point->new( x => $y, y => $x ); } } #### class Cache::LRU { use Hash::Ordered; our $num_caches = 0; # class data (unused in this example) my $x = Hash::Ordered->new; # private instance data has UInt $max_size = 20; # public instance data method set ( Str $key, $value ) { if ( $x->exists($key) ) { $x->delete($key); } elsif ( $x->keys > $max_size ) { $x->shift; } $x->set( $key, $value ); } method get ( Str $key) { return unless $x->exists($key); return $x->set( $key, $x->delete($key) ); } } #### package Cache::LRU { use Hash::Ordered; use Moose; use MooseX::Types::Common::Numeric qw/PositiveOrZeroInt/; use Carp ‘croak’; use namespace::autoclean; has '_cache' => ( is => 'ro', isa => 'Hash::Ordered', default => sub { Hash::Ordered->new }, ); has 'max_size' => ( is => 'ro', isa => PositiveOrZeroInt, default => 20, ); sub set { croak('…') unless @_ == 3; my ( $self, $key, $value ) = @_; if ( $self->_cache->exists($value) ) { $self->_cache->delete($value); } elsif ( $self->_cache->keys > $self->max_size ) { $self->_cache->shift; } $self->_cache->set( $key, $value ); } sub get { croak('…') unless @_ == 2; my ( $self, $key ) = @_; if ( $self->{cache}->exists($key) ) { my $value = $self->_cache->delete($key); $self->_cache->set($key,$value); return $value; } return; } __PACKAGE__->meta->make_immutable; }