Vocabulary/fordot

From J Wiki
Jump to: navigation, search

>> <<   Back to: Vocabulary Thru to: Dictionary

for. noun do. body end. Repeat for each item Control
for_ijk. noun do. body end. Repeat for each item, named Control

Valid only inside an explicit definition.


Execute the ensuing block (which starts after the next do.) once for each item of the noun evaluated by the T-block.

   for. i. nloops do.  NB. loop nloops times
<loop body>
   end.

   for_i. 'for';'each';'word' do.  loop 3 times, with i assuming the value of the words successively
<loop body>
   end.

Use (for_ijk.) instead of (for.) to give a name to the current item. At each iteration…

  • (ijk) takes the value of the current item
  • (ijk_index) takes the value: (0, 1, 2, …) in turn.

(ijk) (here) is a representative pronoun whose value you can inspect (read-only) at each iteration. Substitute your own choice of name, e.g. (i) , (i_index)

If you use for. with no name, the loop will be executed once for each item of the T-block, and the actual values in the T-block are immaterial.


Common uses

1. Execute a given block 3 times

3 : 0''
for. i.3 do.
  smoutput 'alpha'
end.
)
alpha
alpha
alpha

When you use (for.) the statements within the block can't see the actual items of the T-block

2. Execute a given block once for each item of a given noun, viz. (0.5 + i.3) inspecting its value in turn, also its index in the list

3 : 0''
for_ijk. 0.5 + i.3 do.
  smoutput 'bravo' ; ijk ; ijk_index
end.
)
┌─────┬───┬─┐
│bravo│0.5│0│
└─────┴───┴─┘
┌─────┬───┬─┐
│bravo│1.5│1│
└─────┴───┴─┘
┌─────┬───┬─┐
│bravo│2.5│2│
└─────┴───┴─┘

Details

  1. The result of the T-block, which gives the values to be repeated over, may be a noun of any rank. The loop is executed once for each item of the T-block.
  2. At the end of a for_ijk. loop, the names ijk and ijk_index remain defined. If the loop was exited by break. or goto., the names simply retain their latest values. If the loop is exited by executing all the iterations, ijk is set to an empty list and ijk_index is set to the number of iterations that were executed.

Related Primitives

Use these control words inside the loop…