문제

I am a newbie and try to learn J. There is one question I have had for quite some time.

What is the statement separator in J? Can I write several statements in the same line in J?

도움이 되었습니까?

해결책 2

As MPelletier notes, there is no statement operator but you can use the "assignment trick": assign the result of a statement to a variable when you use it, the first time (from right to left) that you use it. Eg:

Instead of this:

a =: 15
f =: (+/) % # i.a
g =: (-/) % # i.a
h =: ((-:g) * (+:f)) ^ ((-:f) * (+:g))

you can write this:

h =: ((-:g) * (+:f)) ^ ((-: f =. (+/) % #i.a) * (+: g =. (-/) % # i.a=.15))

Or, instead of:

mean =: (+/) % #
f =: mean i.15

this:

f =: (mean =: (+/) % #) i.15

다른 팁

Although the statement separator in J is the linefeed, you can separate assignment statements on a single line by using the Left verb (dyadic [) which always returns its left argument. Since J parses right to left, the Left verb effectively breaks up statements as the right argument is discarded (although side effects such as assignment still occur).

   2 + 3 [ t=. 3 + 4
5
  t
7

So in this case t is assigned 7 and then 3 [ t is evaluated returning 3 which is added to 2. In contrast if you use Right (dyadic ]) you may be swimming upstream with different results.

   2 + 3 ] t=. 6 + 4
12
   t
10

Here t is assigned 10 and the result of 3 ] t is t with a value of 10 which is then added to 2.

Hope this helps, bob

There is no statement separator. Or rather, the statement separator is a line feed.

Alternative to Do "., you can create an anonymous verb with Explicit Verb 3 : and invoke it. This way you don't need to worry about leaked temporary variables.

For multiple statements, you have some way:

  1. Reverse statements and join with [ (ex. 'bar =. foo + 54 [ foo =. 42' )
  2. Concat with line feeds (ex. 'foo =. 42' , LF , 'bar =. foo + 54')
  3. Shape code as a table (ex. 'foo =. 42' ,: 'bar =. foo + 54').

Borrowing Eelvex's example:

   (3 : 'h =. ((-:g) * (+:f)) ^ ((-:f) * (+:g)) [ g =. (-/) % # i.a [ f =. (+/) % # i.a [ a =. 15') ''
0.976216
   (3 : ('a =. 15' ,LF, 'f =. (+/) % # i.a' ,LF, 'g =. (-/) % # i.a' ,LF, 'h =. ((-:g) * (+:f)) ^ ((-:f) * (+:g))')) ''
0.976216
   (3 : ('a =. 15' , 'f =. (+/) % # i.a' , 'g =. (-/) % # i.a' ,: 'h =. ((-:g) * (+:f)) ^ ((-:f) * (+:g))')) ''
0.976216

Somehow 3 : <...> gets evaluated before usual right-to-left execution, so you need parentheses for the right hand of :. Using this behavior, you can omit parentheses around 3 : <...>:

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