develooper Front page | perl.perl6.language | Postings from March 2005

Adding linear interpolation to an array

Thread Next
From:
Dave Whipp
Date:
March 7, 2005 13:21
Subject:
Adding linear interpolation to an array
Message ID:
20050307212101.20717.qmail@lists.develooper.com
I was trying to work out how to get non-integer indexes working for an 
array -- initially using linear interpolation, though perhaps later it 
would be generalized. Can anyone comment on whether this simple role 
would work as I expect. Does defining the invocant as "Num @self is 
constant" constrain the application of the role to read-only uses of 
indices? Does the explicit indexing by an "int" typed value ensure that 
it'll be non-recursive under MMD?

   role LinearInterpolation
   {
     multi method Num postcircumfix:«[]» (
         Num @self is constant : Num $real_index)
     {
        int $integer_index = int $real_index;
        Num $first_value = @self[$integer_index];

        return $first_value if $integer_index == $real_index;

        Num $second_value = @self[$integer_index+1];

        Num $delta = $second_value - $first_value;
        Num $weight = $real_index - $integer_index;

        return $first_value + $delta * $weight;
     }
   }

   my @test does LinearInterpolation;

   @test[0] = 1;
   @test[1] = 3;

   assert @test[0] == 1;
   assert @test[0.5] == 2;
   assert @test[1] == 3;


If I later decare a sub as

   sub foo ( @in does LinearInterpolation ) { ... }

Would I be able to pass a normal (non-interpolating) array to this sub, 
and then access it using non-integer indices (i.e. is the data in the 
array independent of the interface through wich it is accessed).


Dave.

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About