-
Notifications
You must be signed in to change notification settings - Fork 2
/
pwlf.pl
executable file
·78 lines (54 loc) · 1.26 KB
/
pwlf.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package pwlf;
use warnings;
use strict;
use Contextual::Return;
sub new
{
my $self = bless {}, shift();
return CODEREF { sub { $self->_value(@_) } } DEFAULT { $self };
}
sub insert
{
my ($self, $key, $val) = @_;
$self->{'_data'}{$key} = $val;
}
sub _value
{
my ($self, $key) = @_;
my $x_dn = 0;
my $x_up = 2;
my $lower = $self->{'_data'}{$x_dn};
my $upper = $self->{'_data'}{$x_up};
my $interp = sub
{
my $k = shift();
$lower = ref $lower ? $lower->_value($k) : $lower;
$upper = ref $upper ? $upper->_value($k) : $upper;
return mx_plus_b( $key, $x_dn, $x_up, $lower, $upper );
};
my $recurse = ref $lower || ref $upper;
return $recurse
? $interp
: $interp->($key);
}
sub mx_plus_b
{
my ( $x, $x_dn, $x_up, $y_dn, $y_up ) = @_;
my $slope = ( $y_up - $y_dn ) / ( $x_up - $x_dn );
my $intercept = $y_up - ( $slope * $x_up );
my $y = $slope * $x + $intercept;
return $y;
}
package main;
use warnings;
use strict;
my $pwlf = pwlf->new;
$pwlf->insert(0, 0);
$pwlf->insert(2, 2);
my $pwlf2 = pwlf->new;
$pwlf2->insert(0, 0);
$pwlf2->insert(2, 4);
my $pwlf3 = pwlf->new;
$pwlf3->insert(0, $pwlf);
$pwlf3->insert(2, $pwlf2);
print $pwlf3->(1)(2), "\n";