Skip to content

Commit

Permalink
- Renamed the Array .split method to .segment, which better refle…
Browse files Browse the repository at this point in the history
…cts its functionality.

Example:

	func consecutive_partitions(array, callback) {
	    for k in (0..array.len) {
	        combinations(array.len, k, {|*indices|
	            var t = segment(array, indices...)
	            if (t.sum_by{.len} == array.len) {
        	        callback(t)
	            }
        	})
	    }
	}

	var arr = [1,2,3,4,5]
	consecutive_partitions(arr, { .say })

Output:

[[1, 2, 3, 4, 5]]
[[1], [2, 3, 4, 5]]
[[1, 2], [3, 4, 5]]
[[1, 2, 3], [4, 5]]
[[1, 2, 3, 4], [5]]
[[1], [2], [3, 4, 5]]
[[1], [2, 3], [4, 5]]
[[1], [2, 3, 4], [5]]
[[1, 2], [3], [4, 5]]
[[1, 2], [3, 4], [5]]
[[1, 2, 3], [4], [5]]
[[1], [2], [3], [4, 5]]
[[1], [2], [3, 4], [5]]
[[1], [2, 3], [4], [5]]
[[1, 2], [3], [4], [5]]
[[1], [2], [3], [4], [5]]

- Added the new Array `.split(obj)` method, which splits a given array by the given object.

Example:

	say [1,2,0,3,0,4].split(0)		#=> [[1, 2], [3], [4]]

When a block is given for the object, the `.split_by{...}` method is called.

	say [1,2,0,3,0,4].split { _ == 0 }	#=> [[1, 2], [3], [4]]
  • Loading branch information
trizen committed Sep 20, 2019
1 parent 131b84b commit baf967d
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
29 changes: 28 additions & 1 deletion lib/Sidef/Types/Array/Array.pm
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@ package Sidef::Types::Array::Array {

*partition = \∂

sub split {
sub segment {
my ($self, @indices) = @_;

my @parts;
Expand Down Expand Up @@ -445,6 +445,33 @@ package Sidef::Types::Array::Array {
bless \@array;
}

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

if (ref($obj) eq 'Sidef::Types::Block::Block') {
goto &split_by;
}

my @tmp;
my @array;

foreach my $item (@$self) {
if ($item eq $obj) {
CORE::push(@array, [CORE::splice(@tmp)]);
}
else {
CORE::push(@tmp, $item);
}
}

if (@tmp) {
CORE::push(@array, \@tmp);
}

@array = map { bless $_ } @array;
bless \@array;
}

sub or {
my ($self, $array) = @_;

Expand Down
8 changes: 8 additions & 0 deletions lib/Sidef/Types/Array/Array.pod
Original file line number Diff line number Diff line change
Expand Up @@ -1616,6 +1616,14 @@ Aliases: I<scalar_div>

=cut

=head2 segment

Array.segment() -> I<Obj>

Return the

=cut

=head2 shift

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

0 comments on commit baf967d

Please sign in to comment.