Skip to content

Instantly share code, notes, and snippets.

@0racle
Created December 18, 2020 23:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0racle/c57fc86a0a04215c1f253a8a435872b1 to your computer and use it in GitHub Desktop.
Save 0racle/c57fc86a0a04215c1f253a8a435872b1 to your computer and use it in GitHub Desktop.
multi split-on(&f, @xs, :$A!) {
    (-1, |@xs.grep(:k, &f), |@xs.elems)
      .rotor(2 => -1)
      .map(-> ($a, $b) { @xs[$a ^..^ $b] });
}

multi split-on(&f, @xs, :$B!) {
    my $taken = 0;
    gather {
        for @xs.grep(:k, &f) -> $i {
            take @xs[$taken ..^ $i];
            $taken = $i + 1;
        }
        take @xs[$taken .. *]
    }
}

multi split-on(&f, $xs, :$C!) {
    my $iter = $xs.cache.iterator;
    my $taken = 0;
    gather {
        for $xs.grep(:k, &f) -> $i {
            take ($iter.pull-one for ^($i - $taken));
            $taken = $i + $iter.skip-one;
        }
        take ($iter.pull-one for ^($xs.elems - $taken));
    }
}

my @ns = [1, 3, -4, 5, 7, -9, 0, 2];

say split-on(* < 0, @ns, :A);
say split-on(* < 0, @ns, :B);
say split-on(* < 0, @ns, :C);

# Result: ((1 3) (5 7) (0 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment