Loops/Foreach: Difference between revisions

Added Bracmat
(Added Bracmat)
Line 253:
print strs[i]
}</lang>
 
=={{header|Bracmat}}==
Bracmat has a more or less traditional 'while' loop (<code>whl'<i>expression</i></code>) which was introduced rather late in the history of Bracmat. Before that, tail recursion was a way to repeat something.
But let us make a list first:
<lang> ( list
= Afrikaans
Ελληνικά
עברית
മലയാളം
ئۇيغۇرچە
)
</lang>
The 'while' solution. Use an auxiliary variable <code>L</code> that gets its head chopped off until nothing is left:
<lang> !list:?L
& whl'(!L:%?language ?L&out$!language)
</lang>
The tail-recursive solution. When the auxiliary variable is reduced to nothing, the loop fails. By adding the <code>~</code> flag to the initial invocation, failure is turned into success. This solution benefits from tail recursion optimization.
<lang> !list:?L
& ( loop
= !L:%?language ?L
& out$!language
& !loop
)
& ~!loop
</lang>
A completly different way of iteration is by using a pattern that matches an element in the list, does something useful as a side effect and then fails, forcing bracmat to backtrack and try the next element in the list. The <code>@</code> flag matches at most one element. The <code>%</code> flag matches at least one element. Together they ensure that exactly one language name is assigned to the variable <code>language</code>. After all elements have been done, control is passed to the rhs of the <code>|</code> operator.
<lang> ( !list
: ? (%@?language&out$!language&~) ?
|
)
</lang>
 
 
=={{header|C}}==
483

edits