andrewnc
andrewnc

Reputation: 105

Each prior adverb in J

In Q/kdb you can modify a verb easily with ': which represents each-prior. It will apply the verb to an element and it's previous neighbor. For example

=': checks if pairs of values are equal. In J, you can easily fold /\ but it is cumulative, is there a pairwise version of this?

Upvotes: 3

Views: 146

Answers (1)

Julian Fondren
Julian Fondren

Reputation: 5609

\ has a dyadic valence to select lists of a particular length, with different behavior depending on positive and negative lengths:

   2]\i.4
0 1
1 2
2 3
   3]\i.4
0 1 2
1 2 3
   _2]\i.4
0 1
2 3
   _3]\i.4
0 1 2
3 0 0

So for comparing pairs:

   n=:1 2 2 2 3 3 1
   2]\n
1 2
2 2
2 2
2 3
3 3
3 1
   =/"(1) 2]\n
0 1 1 0 1 0
   _2]\n
1 2
2 2
3 3
1 0
   =/"(1) _2]\n
0 1 1 0

With care for the last pair, you could also rotate the list:

   n ,: n
1 2 2 2 3 3 1
1 2 2 2 3 3 1
   (] ,: 1&|.) n
1 2 2 2 3 3 1
2 2 2 3 3 1 1
   =/(] ,: 1&|.) n
0 1 1 0 1 0 1

If you're particular about getting each item with its previous neighbor:

   2|.\1 2 3 4
2 1
3 2
4 3

There's also the 'subarrays' use of cut:

   2 <;.3 n
┌───┬───┬───┬───┬───┬───┬─┐
│1 2│2 2│2 2│2 3│3 3│3 1│1│
└───┴───┴───┴───┴───┴───┴─┘
   2 <;._3 n
┌───┬───┬───┬───┬───┬───┐
│1 2│2 2│2 2│2 3│3 3│3 1│
└───┴───┴───┴───┴───┴───┘
   2 =/;._3 n
0 1 1 0 1 0

Belatedly, after learning a little bit of Q, this usage of each-prior:

q)deltas 10 15 20
10 5 5
q)\
  -':10 15 20
10 5 5

Is duplicated in J with a similar dyadic use of \:

   <\10 15 20
┌──┬─────┬────────┐
│10│10 15│10 15 20│
└──┴─────┴────────┘
   2 <\10 15 20
┌─────┬─────┐
│10 15│15 20│
└─────┴─────┘
   2 <\0 , 10 15 20
┌────┬─────┬─────┐
│0 10│10 15│15 20│
└────┴─────┴─────┘
   2 -~/\0 , 10 15 20
10 5 5
   deltas =: 2 -~/\ 0&,
   deltas 10 15 20
10 5 5

Upvotes: 4

Related Questions