Underspecified, as you appear to be using odd definitions of one or more terms.
The straightforward interpretation of consecutive_differences (a, b, c, ... y, z)
would be ((a - b), (b - c), ... (y - z)).
Parsing the phrase "sum of consecutive differences of (2, 4, 5, 7)" as
"sum (consecutive_differences (2, 4, 5, 6)))" and evaluating, one gets
sum (consecutive_differences(2, 4, 5, 7))
= {definition of consecutive_differences}
sum((2 - 4), (4 - 5), (5 - 7))
= {evaluate sub-expressions}
sum(-2, -1, -2)
= {evaluate sum}
-5
but recognizing sum(a, b, c, ... z) as (a + b + c + ... + z), the above simplifies algebraically to
sum (consecutive_differences(2, 4, 5, 7))
= {definition of consecutive differences}
sum((2 - 4), (4 - 5), (5 - 7))
= {definition of sum}
((2 - 4) + (4 - 5) + (5 - 7))
= {subtraction equals addition of negative}
(2 + -4 + 4 + -5 + 5 + -7)
= {associativity and symmetry of addition}
(2 + (4 - 4) + (5 - 5) - 7)
= {removal of zero terms}
(2 - 7)
= {arithmetic}
-5
so that the "sum of consecutive differences" is the first minus the last.
| [reply] [d/l] [select] |
print eval join'-',@numbers
How do you get -10 from "2-4-5-7"?
| [reply] [d/l] |
@num = (2, 4, 5, 7);
use List::Util "reduce";
$lsub = reduce { $a - $b } @num;
$asum = reduce { $b - $a } reverse @num;
$coeff = do { my @y = @num; while (1 < @y) { $y[$_] -= $y[$_ + 1] for
+0 .. @y - 2; splice @y, -1; } $y[0] };
print "lisp difference: $lsub\nalternating sum: $asum\nhighest coeff:
+$coeff\n";
===>
lisp difference: -14
alternating sum: -4
highest coeff: -2
| [reply] [d/l] [select] |
sub get_neg_10_outta_these {
my $n = shift;
my $sum;
$sum += $n - $_ for (@_);
return $sum;
}
my @nums = (2, 4, 5, 7);
print get_neg_10_outta_these(@nums),"\n";
-sauoq
"My two cents aren't worth a dime.";
| [reply] [d/l] |
@_ = qw( 2 4 5 7 );
$_ = eval join '-', @_;
print
#stdout -14 and not -10
| [reply] [d/l] |
eval should be used sparingly
| [reply] |