This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Upgrade to Scalar-List-Utils 1.45 from CPAN
[perl5.git] / cpan / Scalar-List-Utils / t / sum.t
CommitLineData
1bfb5477
GB
1#!./perl
2
b823713c
CBW
3use strict;
4use warnings;
f4a2945e 5
e8164ee7 6use Test::More tests => 17;
1bfb5477 7
b823713c 8use Config;
f4a2945e
JH
9use List::Util qw(sum);
10
cf083cf9
GB
11my $v = sum;
12is( $v, undef, 'no args');
f4a2945e 13
cf083cf9
GB
14$v = sum(9);
15is( $v, 9, 'one arg');
f4a2945e 16
cf083cf9
GB
17$v = sum(1,2,3,4);
18is( $v, 10, '4 args');
f4a2945e 19
cf083cf9
GB
20$v = sum(-1);
21is( $v, -1, 'one -1');
aaaf1885
GB
22
23my $x = -3;
24
cf083cf9
GB
25$v = sum($x, 3);
26is( $v, 0, 'variable arg');
aaaf1885 27
cf083cf9
GB
28$v = sum(-3.5,3);
29is( $v, -0.5, 'real numbers');
aaaf1885 30
b823713c
CBW
31$v = sum(3,-3.5);
32is( $v, -0.5, 'initial integer, then real');
33
2ff28616
GB
34my $one = Foo->new(1);
35my $two = Foo->new(2);
36my $thr = Foo->new(3);
37
38$v = sum($one,$two,$thr);
39is($v, 6, 'overload');
40
41
42{ package Foo;
43
44use overload
45 '""' => sub { ${$_[0]} },
8c167fd9 46 '0+' => sub { ${$_[0]} },
2ff28616
GB
47 fallback => 1;
48 sub new {
49 my $class = shift;
50 my $value = shift;
51 bless \$value, $class;
52 }
53}
54
3630f57e
CBW
55use Math::BigInt;
56my $v1 = Math::BigInt->new(2) ** Math::BigInt->new(65);
57my $v2 = $v1 - 1;
58$v = sum($v1,$v2);
59is($v, $v1 + $v2, 'bigint');
2ff28616 60
3630f57e
CBW
61$v = sum(42, $v1);
62is($v, $v1 + 42, 'bigint + builtin int');
63
64$v = sum(42, $v1, 2);
65is($v, $v1 + 42 + 2, 'bigint + builtin int');
66
67{ package example;
68
69 use overload
70 '0+' => sub { $_[0][0] },
71 '""' => sub { my $r = "$_[0][0]"; $r = "+$r" unless $r =~ m/^\-/; $r .= " [$_[0][1]]"; $r },
72 fallback => 1;
73
74 sub new {
75 my $class = shift;
76
77 my $this = bless [@_], $class;
78
79 return $this;
80 }
81}
82
83{
84 my $e1 = example->new(7, "test");
b823713c 85 my $t = sum($e1, 7, 7);
3630f57e
CBW
86 is($t, 21, 'overload returning non-overload');
87 $t = sum(8, $e1, 8);
88 is($t, 23, 'overload returning non-overload');
89 $t = sum(9, 9, $e1);
90 is($t, 25, 'overload returning non-overload');
2ff28616 91}
b823713c
CBW
92
93SKIP: {
e8164ee7 94 skip "IV is not at least 64bit", 3 unless $Config{ivsize} >= 8;
b823713c
CBW
95
96 # Sum using NV will only preserve 53 bits of integer precision
97 my $t = sum(1<<60, 1);
98 cmp_ok($t, '>', 1<<60, 'sum uses IV where it can');
e8164ee7
JH
99
100 my $min = -(1<<63);
101 my $max = (1<<63)-1;
102
103 $t = sum($min, $max);
104 is($t, -1, 'min + max');
105 $t = sum($max, $min);
106 is($t, -1, 'max + min');
b823713c 107}