J creating function

I was just starting to learn J, and I tried to create a function that checks if a number is prime.

<./<./13|*/~(2}.i.)13

This checks if 13 is prime and will return 1.

<./<./10|*/~(2}.i.)10

And that will return 0.

So my question is: how do I make a function out of this? How to specify an argument?

prime(x) =: <./<./x|*/~(2}.i.)x

This, of course, will not work. But how can I create this function in J?

PS. I know that the function does not work on 2, I will deal with this later: D

+3
source share
1 answer

To replace specific values ​​in these sentences with a named parameter, you can use a script, for example:

   prime=: verb :'<./<./y|*/~(2}.i.)y'
   prime 13
1
   prime 10
0

( "" - 3. , script - . pattern 'verb:' script.)

, y, x, . J - x ( ) , y.

J , , , , , -, . :

   prime=: (verb :'<./<./y|*/~(2}.i.)y')"0
   prime 10 11 12 13
0 1 0 1

</( ) , :

   prime=: (verb :'<./ , y|*/~(2}.i.)y')"0

, , , , , , J-. , p:, . , :

   prime=: verb :'1 p: y'

, "y" ( "prime" ).

: , . script, . 'x' 'y' , . , "y".

J . script, , . ( , .) "" , .

+6

Source: https://habr.com/ru/post/1776105/


All Articles