Use a verb waiting for a scalar with a vector

I created a dyadic verb that expects a number and a vector and returns a vector filtered to contain those that divide the number, for example:

divs =. 4 : '((=<.)y%x)#y' 

So, for example, 4 divs i.20 returns 0 4 8 12 16 as expected.

Now I would like to change / wrap this verb so that the first argument could be a vector, and return either a two-dimensional vector or one long one. I'm interested in how to implement both. Therefore, I would like to be able to do this:

 4 5 divs2 i.20 

and return my verb:

 0 4 8 16 20 0 5 10 15 

or

 0 4 8 16 20 0 5 10 15 

Something like map or mapcat or flatmap from FP languages. How can I achieve this?

EDIT: to be clear, I hope for 2 new verbs (not one that can give both results)

+4
source share
2 answers

I will come back later and edit this with justification, but as an immediate answer, you want:

  divs2=.divs"0 1 NB. Parcel left args into scalars, right into vectors 4 5 divs2 i.20 NB. Note fill element (trailing zero) 0 4 8 12 16 0 5 10 15 0 divs3=.[: ; <@divs2 NB. Like divs2, but single flat list 4 5 divs3 i.20 NB. Note the <@ prevents the fills (no trailing zero) 0 4 8 12 16 0 5 10 15 
+4
source

J has a Residue (|) primitive that makes it a little easier (it saves me the need to share and then compare the result - an integer to determine the factors).

In implicit form

  divt=: ((0=|)#])"0 1 4 5 divt i. 20 0 4 8 12 16 0 5 10 15 0 

Explicit

  divE=: 4 : '((0 = x|y) # y)'"0 1 4 5 divE i. 20 0 4 8 12 16 0 5 10 15 0 

I often find that J already has a primitive that does at least some of the work for me when I code.

+3
source

All Articles