J language is getting closer to people

A distinctive feature of the J language is the ability to write iterative algorithms without explicitly using loops and recursion. For example, the sum of all array elements is solved as " +/", and the average of all array elements is " +/%#".



Various reviews of J have already been published on Habrรฉ more than once. For example in this article and in this one .



J is a language with a 30-year history and is still developing and improving. However, there was only one โ€œwhite spotโ€ in J - iterative algorithms with conditional stop. For this, it was suggested to use the while construction. paired with break. and continue.



Using while. in J looks redundant and awkward. And, in addition, it seriously sags in speed in comparison with tacit forms.



And in the 9th version of the language, a new union F was added (named after the first letter of the word "fold").







For comparison, let's solve the problem using while. and using the new union The

condition is simple: get a new array from the original array that contains the doubled values โ€‹โ€‹of the elements. The length of the new array is specified externally and may be less than the original.

First using while.



t =: dyad define
c =. 0
i =. i.x
z =. $0
while. -. c = y
do. 
z =. z , (+: (c { i))
c =. >: c
end.
z
)
10 t 5
    0 2 4 6 8


And now the solution using the new union F. Let's add that the condition for exiting the loop is checked using the verb Z:




COUNT =: 6
v=: dyad define
_2 Z: -.* COUNT =: <: COUNT
x
)
'' +: F:. v (i.10)
    0 2 4 6 8


The documentation promises that F. will be not only more convenient, but also faster while. Eventually, J is getting closer to people!



PS Knowledgeable people may notice that this problem can be easily solved without using both cyclical and new constructions. It is enough to extract a subarray of the required length and then process it in tacit form. However, in real problems it often happens that the length of the subarray is not known in advance and the stop condition is calculated during the operation of the algorithm.



All Articles