Repeat: Difference between revisions

1,245 bytes added ,  9 years ago
jq
m (Added the Sidef language)
(jq)
Line 273:
Example 2
Example 3</pre>
=={{header|jq}}==
{{works with|jq|1.4}}
 
We first define "repeat" naively but in accordance with the task
specification; we then define an optimized version that illustrates
a general technique for taking advantage of jq's support for
tail-call optimization (TCO).
 
Since jq is a purely functional language, repeat(f; n) is unlikely
to be very useful so we define a similar filter, repeatedly(f; n), which
generates n+1 terms: . (the input), f, f|f, ... ; that is, using
conventional functional notation, it generates: x, f(x), f(f(x)), ...
 
'''Unoptimized version''':
<lang jq>def unoptimized_repeat(f; n):
if n <= 0 then empty
else f, repeat(f; n-1)
end;</lang>
 
'''Optimized for TCO''':
<lang jq>def repeat(f; n):
# state: [count, in]
def r:
if .[0] >= n then empty else (.[1] | f), (.[0] += 1 | r) end;
[0, .] | r;</lang>
'''Variant''':
<lang jq># If n is a non-negative integer,
# then emit a stream of (n + 1) terms: ., f, f|f, f|f|f, ...
def repeatedly(f; n):
# state: [count, in]
def r:
if .[0] < 0 then empty else .[1], (.[1] |= f | .[0] -= 1 | r) end;
[n, .] | r;
</lang>
 
'''Examples''':
<lang jq>0 | [ repeat(.+1; 3) ]</lang>
produces:
[1,1,1]
<lang jq>0 | repeatedly(.+1; 3)</lang>
produces:
0
1
2
3
 
=={{header|МК-61/52}}==
2,460

edits