In J, I can update a subset of an array in place according to some predicate, like so:
y (k}~) |. y {~ k =. I. '123' e.~ y =. '[1.2.3]'
[3.2.1]
I realize I can factor out a conjunction here, but is there a more elegant way to do it in the first place? The 123
is just an example. What I want to do, specificially, is:
k
)Also, it's important that the verb operates on the array as a whole, because what I mainly want to do is permute and transform sub-arrays in place. (Hence the |.
in the example.)
Is there a simpler way to do this?
There's a more-or-less standard adverb for this:
tweak =: (@:{) (`[) (`]) }
twist =: |. tweak
'123' (I.@:e.~ twist ]) '[1.2.3]'
[3.2.1]
Here, tweak
uses the gerundial form of }
to:
x
from the array y
using {
.@{
. That is, the {
selects, and the @:
asks for a verb to apply to that selection; twist supplies this verb in the form of |.
(reverse).y
(indicated by ]
) at the same indices x
(indicated by [
).I'll note a couple things:
e.
, is intrinsically unordered, yet your transformation function, |.
, concerns itself solely with order. There's nothing wrong with that, per se, but it might be confusing in the context of reordering parts of an array (consider, e.g., y=.'[1.1.1]'
). Amend
does exactly that. If I'm reading your question right, the following is a simpler way:
v1 =: [: I. e.~ NB. indeces
v0 =: [: |. e.~ # ] NB. transform the subarray
v2 =: ]
'123' (v0`v1`v2) } '[1.2.3]'
[3.2.1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With