The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Sidef::Types::Array::Array

DESCRIPTION

This class implements ...

SYNOPSIS

var obj = Array(...)

INHERITS

Inherits methods from:

       * Sidef::Object::Object

METHODS

&

    a & b

Returns the intersection of two arrays.

    <a a a b c> & <a x y a c>    #=> ["a", "a", "c"]

Aliases: and

*

    a * n

Repeats the content of array a n times, returning a new array.

    <a b> * 2   #=> ["a", "b", "a", "b"]

Aliases: mul

**

    a ** n

Matrix exponentiation, excpecting array a to be a 2D array.

    var A = [[1, 2, 0],
             [0, 3, 1],
             [1, 0, 0]]

    say A**5     #=> [[37, 274, 84], [42, 311, 95], [11, 84, 26]]

Aliases: mpow, matrix_pow

+

    a + b

Array concatenation, returning a new array.

    <a b> + <c d>    #=> ["a", "b", "c", "d"]

Aliases: add, concat

-

    a - b

Array difference: removes any element from array a that exists inside array b, returning a new array.

    <a a a b c> - <a x y a c>       #=> ["a", "b"]

Aliases: sub, diff

...

    a...

Converts array a into a list.

    var (a,b,c) = <1 2 3>...

Aliases: to_list

/

    a / n

Divides the array a into n segments.

If the division is not exact, the remaining incomplete segment is added to the end of the returned array.

    <a b c d>   / 2     #=> [["a", "b"], ["c", "d"]]
    <a b c d e> / 2     #=> [["a", "b"], ["c", "d"], ["e"]]

Aliases: ÷, div

<

    a < b

Less-than array comparison, done term-by-term, returning true or false.

Aliases: lt

<=>

    a <=> b

Array comparison, done term-by-term, returning:

     1 when a > b
     0 when a == b
    -1 when a < b

Aliases: cmp

==

    a == b

Returns true if a and b are equal to each other.

Aliases: eq

>

    a > b

Greater-than array comparison, done term-by-term, returning true or false.

Aliases: gt

^

    a ^ b

Returns the set difference of two arrays.

    <a a a b c> ^ <a x y a c>   #=> ["a", "b", "x", "y"]

Aliases: xor

|

    a | b

Returns the union of two arrays.

    <a a a b c> | <a x y a c>   #=> ["a", "a", "a", "b", "c", "x", "y"]

Aliases: or

|>>

    a |>> b

Returns the

Aliases: pipeline_map_op

|X>

    a |X> (block1, block2, ...)

Pipeline cross-product operator, mapping each element to each given block.

   say ([1,2,3] |X> ({ .cube }, { _+42 }))     #=> [1, 43, 8, 44, 27, 45]

Aliases: pipeline_cross_op

|Z>

    self.|Z>(*callbacks)

Returns the

Aliases: pipeline_zip_op

«

    a « b

Returns the

Aliases: <<, push, append

»

    a » b

Returns the

Aliases: >>, pop, drop_last, drop_right

    a ∋ b

Returns the

Aliases: has, contain, include, contains, includes

    a ∌ b

Returns the

    a ≠ b

Returns the

Aliases: !=, ne

    a ≤ b

Returns the

Aliases: <=, le

    a ≥ b

Returns the

Aliases: >=, ge

abbrev

    arr.abbrev
    arr.abbrev(/pattern/)

Returns an Hash with the unambiguous abbreviations for the given array of strings.

    say ['loved', 'loving', 'lover', 'lost'].abbrev

Output:

    Hash(
        "los"    => "lost",
        "lost"   => "lost",
        "loved"  => "loved",
        "lover"  => "lover",
        "lovi"   => "loving",
        "lovin"  => "loving",
        "loving" => "loving"
    )

When an additionaly regular expression is given, it collects only the abbreviations that will match the regex.

Aliases: abbreviations

acc

    self.acc(block)

Returns the

Aliases: accumulate

acc_by

    self.acc_by(block)

Returns the

Aliases: accumulate_by

all

    self.all(block)

Returns the

all_composite

    self.all_composite

Returns the

all_prime

    self.all_prime

Returns the

any

    self.any(block)

Returns the

avg

    arr.avg

Returns the average of a list of numbers.

    say [1,2,3,4].avg   #=> 2.5

avg_by

    arr.avg_by { ... }

Returns the average of a list of numbers, by mapping each value to a given block of code.

    say [1,2,3,4].avg_by { _**2 }   #=> 7.5

bindex

    arr.bindex(obj)

Returns the index of a given element inside a sorted array, using the Binary Search algorithm.

    var a = ["Alice", "Jane", "Joe", "John", "Kate", "Zerg"]

    say a.bindex('Alice')   #=> 0 (first index)
    say a.bindex('Jane')    #=> 1 (second index)

Aliases: bsearch_index

bindex_by

    arr.bindex_by { ... }

Returns the index of any element inside a sorted array, based on a given comparison block, using the Binary Search algorithm.

    var a = ["Alice", "Jane", "Joe", "John", "Kate", "Zerg"]

    say a.bindex { _ <=> 'Joe' }     #=> 2 (third index)
    say a.bindex { _ <=> 'John' }    #=> 3 (fourth index)

Aliases: bsearch_index_by

bindex_ge

    self.bindex_ge(obj)

Returns the

bindex_ge_by

    self.bindex_ge_by(obj)

Returns the

bindex_le

    self.bindex_le(obj)

Returns the

bindex_le_by

    self.bindex_le_by(obj)

Returns the

bindex_max

    self.bindex_max(obj)

Returns the

bindex_max_by

    self.bindex_max_by(block)

Returns the

bindex_min

    self.bindex_min(obj)

Returns the

bindex_min_by

    self.bindex_min_by(block)

Returns the

binsert

    arr.binsert(obj)

Inserts an element into a sorted array, such that the array will still be sorted.

    var a = ['a', 'b', 'd']
    a.binsert('c')                  # inserts 'c' before 'd'
    say a                           # prints: ['a', 'b', 'c', 'd']

Modifies the array in-place.

binsplit

    arr.binsplit {|a,b| ... }

Applies the binary splitting algorithm to the self-array, returning the result computed using the given block of code.

    say [1,2,3,4,5].binsplit {|a,b| a*b }   #=> 120

bsearch

    self.bsearch(obj)

Returns the

Aliases: bsearch_by

bsearch_ge

    self.bsearch_ge(obj)

Returns the

Aliases: bsearch_ge_by

bsearch_le

    self.bsearch_le(obj)

Returns the

Aliases: bsearch_le_by

bsearch_max

    self.bsearch_max(obj)

Returns the

bsearch_min

    self.bsearch_min(obj)

Returns the

bshuffle

    arr.bshuffle

Shuffles an array in such a way that no element will be on the same position as in the original array (if possible).

Aliases: best_shuffle

cartesian

    arr.cartesian
    arr.cartesian {|*c| ... }

Returns the Cartesian product of a 2D array.

    say [[1,2],[3,4]].cartesian    #=> [[1,3], [1,4], [2,3], [2,4]]

When a block is given, it gets called which each combination:

    [[1,2],[3,4],[5,6]].cartesian {|*c| say c }

Output:

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

cfrac2num

    arr.cfrac2num

Converts a given continued fraction expansion to a number.

    var c = Num.pi.cfrac(10)    # [3, 7, 15, 1, 292, 1, 1, 1, 2, 1]
    say c.cfrac2num.as_frac     #=> 4272943/1360120

change_to

    self.change_to(arg)

Returns the

chrs

    self.chrs(encoding)

Returns the

Aliases: decode, join_bytes

circular_permutations

    self.circular_permutations

Returns the

clear

    self.clear

Returns the

collapse

    self.collapse(initial)

Returns the

combinations

    self.combinations

Returns the

combinations_with_repetition

    self.combinations_with_repetition

Returns the

combine

    self.combine(block)

Returns the

compact

    self.compact

Returns the

cons

    arr.cons(n)

Returns a new array of arrays with n-consecutive elements from the self-array.

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

Aliases: map_cons

contains_all

    self.contains_all(array)

Returns the

contains_any

    self.contains_any(array)

Returns the

contains_type

    self.contains_type(obj)

Returns the

count

    self.count(obj)

Returns the

count_by

    self.count_by(block)

Returns the

cross_op

    self.cross_op(operator, arg)

Returns the

Aliases: cross_operator

defined

    self.defined(index)

Returns the

delete

    self.delete(obj)

Returns the

Aliases: remove

delete_by

    self.delete_by(block)

Returns the

Aliases: delete_if, remove_by, remove_if

delete_first

    self.delete_first(obj)

Returns the

Aliases: remove_first

delete_first_by

    self.delete_first_by(block)

Returns the

Aliases: delete_first_if, remove_first_by, remove_first_if

delete_last

    arr.delete_last(obj)

Removes the last obj element from the array, modifying the array in-place.

    var arr = %w[a b c a]
    arr.delete_last('a')
    say arr                 #=> ["a", "b", "c"]

Returns true if such an element was removed.

Aliases: remove_last

delete_last_by

    self.delete_last_by(block)

Returns the

Aliases: delete_last_if, remove_last_by, remove_last_if

derangements

    self.derangements

Returns the

Aliases: complete_permutations

det

    self.det

Returns the

Aliases: determinant

det_bareiss

    self.det_bareiss

Returns the

diffs

    arr.diffs(n=1)

Returns the n-th differences of the array (calling sub).

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

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

Aliases: differences, nth_differences

dig

    self.dig(key, *keys)

Returns the

digits2num

    arr.digits2num(base=10)

Converts the list of values returned by Number digits(n, base) back to n.

    say 1234.digits.digits2num              #=> 1234
    say [73, 56, 0, 76, 22].digits2num(100) #=> 2276005673

Aliases: from_digits

each_2d

    arr.each_2d {|a,b,c,...| ... }

Iterate over a 2D array.

    [[1,2],[3,4]].each_2d {|a,b|
        say (a**2 + b**2)
    }

each_cons

    arr.each_cons(n, { ... })

Iterate over n consecutive values at a time.

    [1,2,3,4,5,6,7].each_cons(3, {|*c| say c })

Outputs:

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

each_k

    self.each_k(block)

Returns the

Aliases: each_key, each_index

each_kv

    self.each_kv(block)

Returns the

each_slice

    self.each_slice(n, block)

Returns the

end

    self.end

Returns the

Aliases: offset

exists

    self.exists(index)

Returns the

Aliases: has_index

expand

    arr.expand { ... }

Recursively expand an array, given a block of code.

    say [1,[2,[3,4]],5].expand { _ }    #=> [1, 5, 2, 3, 4]

Aliases: expand_by

extract_by

    self.extract_by(block)

Returns the

extract_first_by

    self.extract_first_by(block)

Returns the

extract_last_by

    self.extract_last_by(block)

Returns the

fetch

    arr.fetch(index, default)

Fetches a value at the given index. When the index does not exist, it returns the default value.

    var a = [3,9,27]
    say a.fetch(2, 42)     # fetches index 2 and prints: 27
    say a.fetch(3, 42)     # fails to fetch index 3, therefore prints: 42

find

    self.find(block)

Returns the

Aliases: first_by

flat

    self.flat

Returns the

Aliases: flatten

flat_map

    arr.flat_map { ... }

Similar to .map{}, but it expects the returned block-value to be an array, which will be collected as a list.

    say [1,2,3,4,5].flat_map { .factor }      #=> [2, 3, 2, 2, 5]

flip

    self.flip

Returns the

Aliases: reverse

for

    self.for(block)

Returns the

Aliases: each, foreach

freq

    arr.freq

Returns a frequency Hash for the elements inside the array.

    say ["a","b","a"].freq      #=> Hash(a => 2, b => 1)

freq_by

    self.freq_by(block)

Returns the

ft

    self.ft

Returns the

gauss_jordan_invert

    self.gauss_jordan_invert

Returns the

gauss_jordan_solve

    self.gauss_jordan_solve(vector)

Returns the

gcd

    self.gcd(block)

Returns the

gcd_by

    self.gcd_by(block)

Returns the

gcud

    self.gcud(block)

Returns the

gcud_by

    self.gcud_by(block)

Returns the

getopt

    arr.getopt(...)

Parse an array containing (long) command-line arguments, automatically converting the argument-values based on the types of the default values.

    var file = File('file.dat')
    var length = 42
    var verbose = false

    var args = ['--file', 'foo.txt', '--length', '1234', '--verbose']

    args.getopt(
        'length=i' => \length,
        'file=s'   => \file,
        'verbose!' => \verbose,
    )

    say file.dump           #=> File("foo.txt")
    say length              #=> 1234
    say verbose             #=> true

grep

    self.grep(block)

Returns the

Aliases: select

grep_2d

    arr.grep_2d {|a,b,c,...| ... }

Filtering of a 2D array, given a block of code.

    say [[1,2],[3,4]].grep_2d {|a,b| a+b == 7 }    #=> [[3,4]]

grep_kv

    self.grep_kv(block)

Returns the

Aliases: select_kv

group

    self.group(block)

Returns the

Aliases: group_by

    self.head(arg)

Returns the

Aliases: first

index

    arr.index(obj)
    arr.index { ... }

Returns the first index of a given item inside the array.

    say %w(a b c).index("a")   #=> 0
    say %w(a b c).index("c")   #=> 2

When a block is given, it returns the first index of the element for which the block returns a true value:

    say %w(A B C).index { .lc == 'b' }   #=> 1

Aliases: index_by, first_index, first_index_by

inject

    arr.inject {|a,b| ... }
    arr.inject({|a,b| ... }, obj)

Reduce a given array to a single element, given a block of code that is called with a pair a,b, where a is the previous result returned by the block and b is the current element of the array.

The initial value of a is the first element of the array.

    say [1,2,3,4].reduce {|a,b| a + b }        #=> 10

When an additional argument is given, it will be used as the initial value for a:

    say [1,2,3,4].reduce({|a,b| a + b }, 5)    #=> 15

Aliases: reduce

insert

    self.insert(i, *objects)

Returns the

inv

    self.inv

Returns the

Aliases: invert, inverse

is_empty

    self.is_empty

Returns the

item

    self.item(index)

Returns the

items

    self.items(*indices)

Returns the

iter

    self.iter

Returns the

jaro_distance

    self.jaro_distance(arg, winkler)

Returns the

join

    self.join(delim, block)

Returns the

join_insert

    arr.join_insert(obj)

Inserts the given object between every element of the array. Returns a new array.

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

keys

    arr.keys

Returns an array with the indices of the self-array.

    say ["x","y","z"].keys   #=> [0, 1, 2]

Aliases: indices

keys_by

    arr.keys_by { ... }

Returns an array with the indices for which the given block returns a true value.

    say [41, 42, 43].indices_by { .is_prime }     #=> [0, 2]

Aliases: indices_by

keys_of

    arr.keys_of(obj)

Returns an array with the indices of obj inside the self-array.

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

Aliases: indices_of

kv

    self.kv

Returns the

Aliases: pairs, zip_indices

last

    self.last(arg)

Returns the

Aliases: tail

last_by

    self.last_by(block)

Returns the

last_uniq

    self.last_uniq

Returns the

Aliases: last_unique

last_uniq_by

    self.last_uniq_by(block)

Returns the

Aliases: last_unique_by

lcm

    self.lcm(block)

Returns the

lcm_by

    self.lcm_by(block)

Returns the

len

    self.len

Returns the

Aliases: size, length

lev

    self.lev(arg)

Returns the

Aliases: leven, levenshtein

madd

    m1.madd(m2)

Returns the

Aliases: matrix_add

make

    self.make(size, obj)

Returns the

make_by

    self.make_by(size, block)

Returns the

map

    self.map(block)

Returns the

Aliases: collect

map_2d

    arr.map_2d {|a,b,c,...| ... }

Mapping of a 2D array, given a block of code.

    say [[1,2],[3,4]].map_2d {|a,b| [a**2, b**2] }   #=> [[1, 4], [9, 16]]

map_kv

    self.map_kv(block)

Returns the

Aliases: collect_kv

map_op

    self.map_op(operator, *args)

Returns the

Aliases: map_operator

map_reduce

    arr.map_reduce {|a,b| ... }

Behaves almost like the reduce method, except that all the intermediary terms are returned as an array.

    say [1,2,3,4,5].map_reduce {|a,b| a+b }         #=> [1, 3, 6, 10, 15]
    say [1,2,3,4,5].map_reduce {|a,b| a*b }         #=> [1, 2, 6, 24, 120]

Aliases: reduce_map

match

    arr.match(/regex/)

Recursively match an array against a regular expression.

    say ['a', ['foo'], 'b'].match(/^foo/)

max

    self.max

Returns the

max_by

    self.max_by

Returns the

mdiv

    m1.mdiv(m2)

Returns the

Aliases: matrix_div

min

    self.min

Returns the

min_by

    self.min_by

Returns the

minmax

    self.minmax

Returns the

mmul

    a `mmul` b

Multiply two 2D-matrices, returing a Matrix object.

Example:

    say ([[1, 2],
          [3, 4]] `mmul` [[-3, -8, 3],
                          [-2,  1, 4]])

Output:

    Matrix(
        [-7, -6, 11],
        [-17, -20, 25]
    )

Aliases: matrix_mul

msolve

    self.msolve(vector)

Returns the

Aliases: matrix_solve

msub

    m1.msub(m2)

Returns the

Aliases: matrix_sub

new

    self.new

Returns the

Aliases: call

next_permutation

    arr.next_permutation

It modifies the self array in place to contain the next unique permutation and returns true if there are more permutations available, or false if the current permutation is the last one.

Example:

    var arr = [1,1,2]
    do { say arr } while arr.next_permutation

Output:

    [1, 1, 2]
    [1, 2, 1]
    [2, 1, 1]

none

    arr.none { ... }

Returns true if none of the elements satisfy the condition given in the block of code.

    say [2, 4, 6].none { .is_odd }  #=> true

nth_perm

    arr.nth_perm(n)

Efficiently returns the n-th permuation of the self array.

    say nth_perm([0,1,2,3,4,5,6,7,8,9], 10**6)

Aliases: nth_permutation

ordered_partitions

    arr.ordered_partitions
    arr.ordered_partitions(k)
    arr.ordered_partitions{|*a| ... }
    arr.ordered_partitions(k, {|*a| ... })

Iterates over the ordered partitions P of arr, such that P.flat == arr.

        [1,2,3,4,5].ordered_partitions(2, {|*a| say a })

Outputs:

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

When no block is given, it returns an array containing the ordered partitions (there are binomial(n-1, k-1) ordered partitions, where n is the size of the array):

        say [1,2,3,4].ordered_partitions(2)

Outputs:

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

Additionally, when the value for k is ommited, it generates all the ordered partitions (there are 2^(n-1) ordered partitions, where n is the size of the array):

        [1,2,3,4].ordered_partitions{|*a| say a }

Outputs:

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

Up to the ordering, the method is equivalent with (but more efficient):

        arr.partitions(k).grep { .flat == arr }

pack

    self.pack(format)

Returns the

pair_map

    self.pair_map(block)

Returns the

Aliases: pairmap

pam_op

    arr.pam_op(operator, obj)

Reversed-mapping of the array, given an operator.

    say [1,2,3].pam_operator('/', 10)   # [10/1, 10/2, 10/3]

This method is used internally by the «OP« hyper-operator:

    say ([1,2,3] «/« 10)

Aliases: pam_operator

part

    arr.part(n)

Partition the array into two parts, given an index:

    [1,2,3,4,5].part(3)     # returns: ([1, 2, 3], [4, 5])
    [1,2,3,4,5].part(2)     # returns: ([1, 2], [3, 4, 5])

Negative indices are supported as well:

    [1,2,3,4,5].part(-1)    # returns: ([1, 2, 3, 4], [5])

Aliases: partition

partitions

    self.partitions(k, block)

Returns the

perm2num

    self.perm2num

Returns the

permutations

    self.permutations

Returns the

pick

    self.pick(amount)

Returns the

pop_at

    self.pop_at(offset)

Returns the

Aliases: delete_at, delete_index

pop_rand

    self.pop_rand

Returns the

pop_while

    self.pop_while(block)

Returns the

prepend

    self.prepend(*args)

Returns the

Aliases: unshift

prod

    self.prod(arg)

Returns the

prod_2d

    arr.prod_2d {|a,b,c,...| ... }

Product of a 2D array, by mapping each row to the given block.

    say [[2,4],[3,2],[5,1],[7,1]].prod_2d {|p,k| p**k }    #=> 5040

prod_by

    arr.prod_by { ... }

Product of an array, by mapping each element to the given block.

    say [1,2,3,4].prod_by {|n| n**3 }    # product of each element cubed

prod_kv

    self.prod_kv(block)

Returns the

prodmod

    self.prodmod(mod)

Returns the

rand

    self.rand(amount)

Returns the

Aliases: sample

rand_perm

    arr.rand_perm

Returns a random permutation of the self array.

Example:

    var arr = %w(a b c d e f g)
    say arr.random_permutation

Additionally, by setting a seed value for irand with Number iseed(), the results returned by random_permutation can be reproduced.

Example with iseed():

    iseed(42)
    var arr = %w(a b c d e f g)
    say arr.random_permutation      #=> ["d", "f", "g", "b", "c", "e", "a"]

Aliases: random_permutation

range

    self.range

Returns the

recmap

    arr.recmap { ... }

Recursively map the value of an array, given a block of code.

    # Generate all the 5-smooth numbers <= 20
    var (a, k, L) = ([1], 5, 20)
    k.primes.each {|p| a.recmap! {|n| n*p <= L ? [n*p] : () } }
    say a.sort    #=> [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20]

reduce_op

    self.reduce_op(operator, initial)

Returns the

Aliases: reduce_operator

resize

    arr.resize(index)

Efficienlty resize the array to a given index, modifying the array in-place.

    var arr = %w[a b c d e]
    arr.resize(2)            # removes indices > 2
    say arr                  # ['a', 'b', 'c']

Use index -1 to empty the array.

Aliases: resize_to

rindex

    self.rindex(obj)

Returns the

Aliases: rindex_by, last_index, last_index_by

rotate

    self.rotate(num)

Returns the

rref

    self.rref

Returns the

Aliases: reduced_row_echelon_form

rscalar_op

    self.rscalar_op(operator, scalar)

Returns the

Aliases: rscalar_operator

run_length

    arr.run_length
    arr.run_length { ... }

The run-length algorithm, returning an array of pairs [a,n].

    say [1,1,1,2,3,3].run_length            #=> [[1, 3], [2, 1], [3, 2]]
    say %w(a a b C c c).run_length { .lc }  #=> [['a', 2], ['b', 1], ['C', 3]]

Aliases: run_length_by

sadd

    self.sadd(scalar)

Returns the

Aliases: scalar_add

scalar_op

    self.scalar_op(operator, scalar)

Returns the

Aliases: scalar_operator

sdiv

    self.sdiv(scalar)

Returns the

Aliases: scalar_div

segment

    arr.segment(indices...)

Segment an array at the given indices.

    var arr = [1,2,3,4]
    say arr.segment(1)         #=> [[1, 2], [3, 4]]
    say arr.segment(2)         #=> [[1, 2, 3], [4]]
    say arr.segment(0, 1, 2)   #=> [[1], [2], [3], [4]]
    say arr.segment(0, 2)      #=> [[1], [2, 3], [4]]

Negative indices can be used for couting from the end of the array (e.g.: -1 means the end of the array).

segment_by

    arr.segment_by { ... }

Segment the array into multiple sub-arrays, whenever the block returns a true value.

Example:

    # Segment the array after each prime number
    say @(1..prime(5)).segment_by { .is_prime }

Output:

    [[1, 2], [3], [4, 5], [6, 7], [8, 9, 10, 11]]

shift

    self.shift(num)

Returns the

Aliases: drop_left, drop_first

shift_while

    self.shift_while(block)

Returns the

shuffle

    self.shuffle

Returns the

slice

    arr.slice(offset)
    arr.slice(offset, length)

Extracts a slice out of the self-array and returns it. First entry is at offset zero.

If offset is negative, starts that far back from the end of the array.

If length is omitted, returns everything through the end of the array.

If length is negative, leaves that many entries off the end of the array.

slice_after

    self.slice_after(block)

Returns the

slice_before

    self.slice_before(block)

Returns the

slices

    array.slices(n)

Slices the self-array into multiple sub-arrays, each sub-array having at most n elements.

    say [1,2,3,4].slices(2)         #=> [[1, 2], [3, 4]]
    say [1,2,3,4,5].slices(2)       #=> [[1, 2], [3, 4], [5]]

Aliases: map_slice

smul

    self.smul(scalar)

Returns the

Aliases: scalar_mul

solve_rec_seq

    arr.solve_rec_seq

Attempts to find a minimal linear recurrence that generates the given array of numbers:

    say 30.of { .fibonacci }.solve_rec_seq      #=> [1, 1]
    say 30.of { .square }.solve_rec_seq         #=> [3, -3, 1]
    say 30.of { .faulhaber(2) }.solve_rec_seq   #=> [4, -6, 4, -1]

Aliases: find_linear_recurrence

solve_seq

    arr.solve_seq(offset=0)

Returns a Polynomial object that generates the terms of the given sequence.

Example:

    say 20.of { .square }.solve_seq         #=> x^2
    say 20.of { .faulhaber(2) }.solve_seq   #=> 1/3*x^3 + 1/2*x^2 + 1/6*x

Example with offset:

    say 20.of { (_+10)**3 }.solve_seq       #=> x^3 + 30*x^2 + 300*x + 1000
    say 20.of { (_+10)**3 }.solve_seq(10)   #=> x^3

sort

    arr.sort
    arr.sort {|a,b| ... }

Returns a new sorted array:

    say [3,2,1,4].sort        #=> [1,2,3,4]
    say ['c','a','b'].sort    #=> ['a','b','c']

An optional comparison block can be given, which is called with two elements a and b and must return -1, 0 or 1, corresponding to how a and b must be ordered in the returned array:

    say [3,2,1,4].sort {|a,b| a <=> b }     #=> [1,2,3,4]
    say [3,2,1,4].sort {|a,b| b <=> a }     #=> [4,3,2,1]

sort_by

    arr.sort_by { ... }

Sort an array by mapping each value to the given block.

    [4,3,1,2].sort_by { _ }            # same as .sort()
    [4,3,1,2].sort_by {|n| -n }        # reversed numerical sorting
    %w(foo fo f).sort_by { .len }      # sort array by length

splice

    self.splice(offset, length, *objects)

Returns the

split

    self.split(obj)

Returns the

split_by

    arr.split_by { ... }

Splits the given array by the objects at which the given block returns a true value.

    say [1,2,0,3,0,4].split_by { _ == 0 }   #=> [[1, 2], [3], [4]]

ssub

    self.ssub(scalar)

Returns the

Aliases: scalar_sub

stack

    arr.stack
    arr.stack { ... }

Groups runs of identical elements.

    say <a a a b b c>.stack     #=> [["a", "a", "a"], ["b", "b"], ["c"]

When a block of code is given, the stocking is done based on the mapping of each element to the given block:

    say <A B b A b B A>.stack_by { .uc }

Output:

    [["A"], ["B", "b"], ["A"], ["b", "B"], ["A"]]

Aliases: stack_by

subsets

    self.subsets

Returns the

sum

    self.sum(arg)

Returns the

sum_2d

    arr.sum_2d {|a,b,c,...| ... }

Sum of a 2D array, by mapping each row to the given block.

    say [[2,4],[3,2],[5,1],[7,1]].sum_2d {|p,k| p**k }     #=> 37

sum_by

    arr.sum_by { ... }

Sum of an array, by mapping each element to the given block.

    say [1,2,3,4].sum_by {|n| n**2 }    # sum of each element squared

sum_kv

    self.sum_kv(block)

Returns the

summod

    self.summod(mod)

Returns the

swap

    self.swap(i, j)

Returns the

take_left

    self.take_left(amount)

Returns the

take_right

    self.take_right(amount)

Returns the

to_a

    self.to_a

Returns the

Aliases: to_array

to_bag

    self.to_bag

Returns the

to_h

    self.to_h

Returns the

Aliases: to_hash

to_m

    self.to_m

Returns the

Aliases: to_matrix

to_s

    self.to_s

Returns the

Aliases: dump, to_str

to_set

    self.to_set

Returns the

to_v

    self.to_v

Returns the

Aliases: to_vector

tuples

    self.tuples

Returns the

Aliases: variations

tuples_with_repetition

    self.tuples_with_repetition

Returns the

Aliases: variations_with_repetition

uniq

    self.uniq

Returns the

Aliases: unique, distinct

uniq_by

    self.uniq_by(block)

Returns the

Aliases: unique_by

uniq_permutations

    arr.uniq_permutations
    arr.uniq_permutations { ... }

It uses the next_permutation method to create all the unique permutations of the self-array.

    say [1,1,2].unique_permutations         #=> [[1, 1, 2], [1, 2, 1], [2, 1, 1]

Equivalent with arr.permutations.uniq, but more efficient, as it creates the permutations without duplicates.

The method also accepts a callback block as an optional argument:

    [1,1,2].unique_permutations {|*perm|
        say perm
    }

Output:

    [1, 1, 2]
    [1, 2, 1]
    [2, 1, 1]

Aliases: unique_permutations

uniq_prefs

    self.uniq_prefs(block)

Returns the

Aliases: unique_prefixes

unroll_op

    self.unroll_op(operator, arg)

Returns the

Aliases: unroll_operator

unzip_by

    self.unzip_by(block)

Returns the

weighted_shuffle_by

    self.weighted_shuffle_by(block)

Returns the

wise_op

    m1.wise_op(operator, m2)

Returns the

Aliases: wise_operator

zip

    self.zip(block)

Returns the

Aliases: transpose

zip_by

    self.zip_by(block)

Returns the

zip_op

    self.zip_op(operator, arg)

Returns the

Aliases: zip_operator