use strict; { package Calculator; use List::Util qw/reduce/; sub add { reduce { $a + $b } @_ } sub multiply { reduce { $a * $b } @_ } } { package main; use Test::More tests => 2; # Calculate the fifth triangular number is( Calculator->add(1 .. 5), 15, ); # Calculate five factorial is( Calculator->multiply(1 .. 5), 120, ); }
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Replies are listed 'Best First'.
Re: Spot the deliberate mistake - list-based maths
by BrowserUk (Patriarch) on Apr 26, 2012 at 17:52 UTC
Re: Spot the deliberate mistake - list-based maths
by Tanktalus (Canon) on Apr 26, 2012 at 22:09 UTC
    $ perl x.pl 1..2 ok 1 ok 2

    Ok, so I made a minor change... :-)

    - sub add { reduce { $a + $b } @_ } - sub multiply { reduce { $a * $b } @_ } + use Scalar::Util qw/looks_like_number/; + sub add { reduce { $a + $b } grep looks_like_number($_), +@_ } + sub multiply { reduce { $a * $b } grep looks_like_number($_), +@_ }
    And, no, I don't particularly recommend this remedy. :-)
Re: Spot the deliberate mistake - list-based maths
by choroba (Cardinal) on Apr 26, 2012 at 21:54 UTC
    Years ago, I was bitten by a similar beast when programming AND and OR for an interpreter in Pascal (the zero was coming from a different source, though).