Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

j

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?

like image 860
Gregory Higley Avatar asked May 21 '15 04:05

Gregory Higley


2 Answers

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.

like image 127
Eelvex Avatar answered Sep 21 '22 16:09

Eelvex


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
like image 26
bob Avatar answered Sep 20 '22 16:09

bob