4

I have created a dyadic verb which expects a number and a vector and returns the vector filtered to contain those which divide the number, like this:

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

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

Now I'd like to modify/wrap this verb so that the first argument can be a vector as well, and return either a 2-dimensional vector or a single long one. I'm interested in how to implement both. So I'd like to be able to do this:

4 5 divs2 i.20

and have my verb return:

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'm hoping for 2 new verbs (not a single one which can produce both results)

4

2 回答 2

4

我稍后会回来并根据理由对其进行编辑,但作为一个直接的答案,你想要:

   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
于 2013-09-24T13:33:39.137 回答
3

J 确实有一个 Residue 原语 (|),这使它更简单一些(它使我不必进行除法然后比较结果是用于识别因子的整数)。

以默认形式

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

显式形式

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

我经常发现 J 已经有一个原语,在我编码时它至少为我完成了部分工作。

于 2013-09-24T16:19:42.133 回答