How do I use argument twice in a function in J?

188 views Asked by At

I want to write prime function for purposes of learning J. So far I've come up with this:

=&0+/(=&0)(2+i.(-&2)y)|y

It's working great except that I should store number in y variable.

   y=.5       
   =&0+/(=&0)(2+i.(-&2)y)|y NB. prime cheker
1
   y=.13       
   =&0+/(=&0)(2+i.(-&2)y)|y NB. prime cheker
1
   y=.14
   =&0+/(=&0)(2+i.(-&2)y)|y NB. prime cheker
0

How do I write a function that works what takes argument? i.e. f 13 -> 1

2

There are 2 answers

0
Eelvex On BEST ANSWER

You can just define a verb using : 3.

f =: 3 :'=&0+/(=&0)(2+i.(-&2)y)|y'
f 5
1
f 13
1
f 10
0

When using : 3, y always refers to the right hand argument of the verb.

If you want to define a dyadic verb, use : 4 and x for the left argument.

Btw, you can set the value of a variable anywhere:

   =&0+/(=&0)(2+i.(-&2)y)|y=.5
   1
   =&0+/(=&0)(2+i.(-&2)y)|y=.10
   0
1
Tikkanz On

You might find the Defining Verbs Guide on the J Wiki useful.

As has already been mentioned you can take your sentence and define it as a verb using the following syntax:

isPrime0=: 3 : '=&0+/(=&0)(2+i.(-&2)y)|y'

However it is probably more natural to write it like this:

isPrime1=: 3 : '0 = (+/ 0 = (2 + i. y - 2) | y)'

You could also define a tacit version (doesn't refer to the arguments) like any of the following:

isPrime2=: 0 = [: +/ 0 = ] |~ 2 + [: i. 2 -~ ]
isPrime3=: 0 = [: +/ 0 = ] |~ 2 + i.@:-&2        NB. replace train with verb composed using conjunctions
isPrime4=: 0 = [: +/ 0 = ] |~ i.&.(-&2)          NB. use Under to re-add the 2 after Integers
isPrime5=: 0 -.@e. i.&.(-&2) | ]                 NB. check no zero in result