From J Wiki
Jump to navigation Jump to search

>> <<   Down to: Dyad   Back to: Vocabulary

Z: y Terminate Fold

Rank Infinity -- operates on x and y as a whole -- WHY IS THIS IMPORTANT?

Terminates Fold, in whole or part.

_2 Z: 0   NB. no-op
_2 Z: 1   NB. force termination of overrunning Fold

The phrases (x Z: 1) and (_3 Z: n) are the only ways to terminate F. and F: .

But the primitive Z: can prematurely terminate any Fold, or skip the production of wasted data in any given iteration of Fold.

Common Uses

1. Halt Fold (F:) after COUNT calls of Fold operand u or raise limit error.

    u=: __&$: :(4 : 0)
echo COUNT
_2 Z: -.*COUNT=:COUNT-1
_3 Z: 5      NB. prevent runaway
y+1 return.  NB. sample recurrence relation for Fold

   ]F:u 10 [ COUNT=:3
11 12
   ]F:u 10 [ COUNT=:666
|fold limit
|       ]F:u 10[COUNT=:666

2. Increase computational efficiency by aborting a wasteful computation.

Similar code to #1 except:

  • the x-argument of Z: should be an integer in the list: (_3 _2 _1 0 1).
  • the y-argument of Z: should be a boolean condition detecting a wasteful pass of u.

More Information

The result of (x Z: y) is always $0 (an empty list).

  • If y is 0, no action is performed.
  • If y is 1, the action depends on x as shown in the table below.


 Executed phrase   Effect
  _3 Z: n If the Fold has already started execution of u at least n times, abort the fold with a fold limit error. Otherwise continue.

Useful to ensure that an unlimited fold (viz. F. or F:) does not run forever.

  _2 Z: 1 Execution of the enclosing Fold terminates immediately, with the result being the result after the last execution of v. If nothing has been added to the overall result, a domain error is raised.
  _1 Z: 1 Execution of the current iteration terminates immediately. The next iteration begins with the next new value of x. The value of y in the next iteration is the result of the most recent execution of u that ran to completion. Nothing is added to the overall result for the current iteration.
  0 Z: 1 Execution of the enclosing Fold continues, but the result of the current execution of v is ignored. For Fold Multiple, nothing is added to the overall result. For Fold Single, the result of v does not become the final result.
  1 Z: 1 Execution of the enclosing Fold continues but stops after the next completion of v.