Multidimensional arrays

Multidimensional arrays can be defined as:

1

var A = [

2

[1, 2],

3

[3, 4],

4

[5, 6],

5

[7, 8],

6

]

7

8

var B = [

9

[1, 2, 3],

10

[4, 5, 6],

11

]

Copied!

In Sidef, we have the

`Array.wise_op()`

method, which takes two arbitrary nested arrays and an operator, folding each element (entrywise) with the provided operator, which is also available as `a ~Wop b`

:1

say ([1,2,[3,[4]]] ~W+ [42,43,[44,[45]]]) #=> [43, 45, [47, [49]]]

Copied!

Alternatively:

1

say wise_op([1,2,[3,[4]]], '+', [42,43,[44,[45]]]) #=> [43, 45, [47, [49]]]

Copied!

Scalar operations:

1

A `scalar_add` 42 # scalar addition (aliased as `sadd`)

2

A `scalar_sub` 42 # scalar subtraction (aliased as `ssub`)

3

A `scalar_mul` 42 # scalar multiplication (aliased as `smul`)

4

A `scalar_div` 42 # scalar division (aliased as `sdiv`)

Copied!

This methods are provided by

`Array.scalar_op()`

, which, just like `Array.wise_op()`

, also supports arbitrary nested arrays:1

say ([1,2,[3,[4]]] ~S+ 42) #=> [43, 44, [45, [46]]]

2

say ([1,2,[3,[4]]] ~S* 42) #=> [42, 84, [126, [168]]]

Copied!

...which is equivalent with:

1

say scalar_op([1,2,[3,[4]]], '+', 42) #=> [43, 44, [45, [46]]]

2

say scalar_op([1,2,[3,[4]]], '*', 42) #=> [42, 84, [126, [168]]]

Copied!

Iteration over 2D arrays

The extended

`for-in`

loop provides support for iterating over a 2D-array, which is useful in combination with the cross and zip metaoperators:1

for a,b in ([1,2] ~X [3,4]) {

2

say "#{a} #{b}"

3

}

Copied!

This is equivalent with:

1

[[1,2], [3,4]].cartesian {|a,b|

2

say "#{a} #{b}"

3

}

Copied!

and outputs:

1

1 3

2

1 4

3

2 3

4

2 4

Copied!

Last modified 1yr ago

Copy link

Contents

Iteration over 2D arrays