How to remove an element from a list in J by index?
Asked Answered
N

2

6

The rather verbose fork I came up with is

({. , (>:@[ }. ]))

E.g.,

3 ({. , (>:@[ }. ])) 0 1 2 3 4 5
0 1 2 4 5

Works great, but is there a more idiomatic way? What is the usual way to do this in J?

Nickolas answered 21/5, 2015 at 4:40 Comment(0)
L
5

Yes, the J-way is to use a 3-level boxing:

(<<<5) { i.10
0 1 2 3 4 6 7 8 9

(<<<1 3) { i.10
0 2 4 5 6 7 8 9

It's a small note in the dictionary for {:

Note that the result in the very last dyadic example, that is, (<<<_1){m , is all except the last item.

and a bit more in Learning J: Chapter 6 - Indexing: 6.2.5 Excluding Things.

Lifton answered 21/5, 2015 at 7:59 Comment(2)
It's a very unusual syntax but definitely simpler than my way.Nickolas
Your way is significantly more efficient for removing one item. It's probably the most efficient (at least between using {, ;. or /.).Lifton
S
4

Another approach is to use the monadic and dyadic forms of # (Tally and Copy). This idiom of using Copy to remove an item is something that I use frequently.

The hook (i. i.@#) uses Tally (monadic #) and monadic and dyadic i. (Integers and Index of) to generate the filter string:

   2 (i. i.@#) 'abcde'
1 1 0 1 1

which Copy (dyadic #) uses to omit the appropriate item.

   2 ((i. i.@#) # ]) 0 1 2 3 4 5
0 1 3 4 5
   2 ((i. i.@#) # ]) 'abcde'
abde
Scenic answered 21/5, 2015 at 15:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.