문제

I just started learning 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 this will return 0.

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

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

This, ofcourse, won't work. But how can I create this function in J?

PS. I know the function doesn't work for 2, I'll deal with that later :D

도움이 되었습니까?

해결책

In order to replace the specific values in those sentences with a named parameter you may use a script, like this:

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

(Here the word 'verb' is merely 3. It acts as the left parameter to the colon, while the script body is the colon's right parameter. But feel free to ignore that detail for awhile, and treat as a pattern 'verb :' before the quoted body of a script.)

You'll notice I've used y, not x, as the parameter name. In explicit J form the left parameter is x (when there is one) and the right parameter, y.

It's natural in J for a verb to receive arrays of indefinite shape, but the one defined above will error if given anything but a scalar. Here's a way to fix that:

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

As a stylistic matter, the repetition of <./ (least among) might not communicate your intent as well as this:

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

I'd like to mention that while programs like this are great for exploring the language, qualifying whether a number is prime is handled by a J primary. That symbol, p: , would normally be used. If an assigned name was desired, and explicit form chosen, here's a typical definition:

   prime=: verb :'1 p: y'

As before, 'y' will be interpreted as the value of the right parameter of the named verb ("prime").

In summary: To specify arguments, in place of particular values, explicit form is used. That involves a script, i.e. text. In explicit verbs write 'x' and 'y' as left and right arguments, respectively. If you use only one argument, it is 'y'.

J programmers often use tacit form, instead. In tacit form there is no script, and arguments are always implied, not specified. (There's no problem with working in explicit form when that is more comfortable.) "Explicit" is so called because, in that form, arguments are indicated explicitly.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top