Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Sir, Suppose I have this list,
@numbers = (2,4,5,7);
What's the quick way to return the sum of consecutive difference of it, in Perl?
#Difference = 2 - 4 - 5 -7 $ans = -10

Replies are listed 'Best First'.
Re: Finding Sum of Consecutive Numerical Difference in Set of Numbers
by Anonymous Monk on Oct 29, 2005 at 13:43 UTC
    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.
Re: Finding Sum of Consecutive Numerical Difference in Set of Numbers
by BUU (Prior) on Oct 29, 2005 at 10:01 UTC
    print eval join'-',@numbers

    How do you get -10 from "2-4-5-7"?

      I wonder too. I can get -4, -14, or -2, but not -10.

      @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

        Here's a -10...

        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.";
        
Re: Finding Sum of Consecutive Numerical Difference in Set of Numbers
by sh1tn (Priest) on Oct 29, 2005 at 10:18 UTC
    @_ = qw( 2 4 5 7 ); $_ = eval join '-', @_; print #stdout -14 and not -10


      eval should be used sparingly