Skip to content

Commit

Permalink
- Added the Array .differences(n=1) method.
Browse files Browse the repository at this point in the history
It returns the n-th differences of the array (calling `sub`).

Example:

	var a = [43, 97, 128, 999]

	say a.diffs			#=> [54, 31, 871]
	say a.diffs(2)			#=> [-23, 840]
	say a.diffs(3)			#=> [863]

- Added the Array `acc` and `acc_by` aliases for methods `accumulator` and `accumulator_by`.
  • Loading branch information
trizen committed Jul 16, 2020
1 parent c69551a commit 1f12152
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 4 deletions.
24 changes: 24 additions & 0 deletions lib/Sidef/Types/Array/Array.pm
Original file line number Diff line number Diff line change
Expand Up @@ -2250,6 +2250,8 @@ package Sidef::Types::Array::Array {
bless \@acc, ref($self);
}

*acc_by = \&accumulate_by;

sub accumulate {
my ($self, $block) = @_;

Expand All @@ -2272,6 +2274,28 @@ package Sidef::Types::Array::Array {
bless \@acc, ref($self);
}

*acc = \&accumulate;

sub differences {
my ($self, $n) = @_;

if (defined($n)) {
$n = CORE::int($n);
}
else {
$n = 1;
}

foreach my $i (1 .. $n) {
$self = $self->map_cons(2, Sidef::Types::Block::Block->new(code => sub { $_[1]->sub($_[0]) }));
}

$self;
}

*diffs = \&differences;
*nth_differences = \&differences;

sub reduce {
my ($self, $obj, $initial) = @_;

Expand Down
22 changes: 18 additions & 4 deletions lib/Sidef/Types/Array/Array.pod
Original file line number Diff line number Diff line change
Expand Up @@ -260,20 +260,24 @@ Aliases: I<abbreviations>

=cut

=head2 accumulate
=head2 acc

Array.accumulate() -> I<Obj>
Array.acc() -> I<Obj>

Return the

Aliases: I<accumulate>

=cut

=head2 accumulate_by
=head2 acc_by

Array.accumulate_by() -> I<Obj>
Array.acc_by() -> I<Obj>

Return the

Aliases: I<accumulate_by>

=cut

=head2 all
Expand Down Expand Up @@ -670,6 +674,16 @@ Return the

=cut

=head2 diffs

Array.diffs() -> I<Obj>

Return the

Aliases: I<differences>, I<nth_differences>

=cut

=head2 dig

Array.dig() -> I<Obj>
Expand Down

0 comments on commit 1f12152

Please sign in to comment.