Generator/Exponential: Difference between revisions

→‎{{header|J}}: new task definition
(→‎{{header|J}}: Clarification to task description invalidated non-generator solution. Please also refer to talk pag.)
(→‎{{header|J}}: new task definition)
Line 36:
=={{header|J}}==
 
Generators are not very natural, in J, because they avoid the use of arrays and instead rely on sequential processing.
Here is a natural implementation of a generator (with the caveat that generators are not very natural, in J):
 
<langHere j>coclassis a 'generator' for mth powers of a number:
 
<lang j>coclass 'mthPower'
n N=:0
next create=:3 :0
nM=: n+1y
)
next=:3 :0
_1 + n=:n+1.N
N=:N+1
n^M
)</lang>
 
And, here are corresponding square and cube generators
next=:3 :0
while.-. ((-: <.&.(^&1r2)) *. -.@(-: <.&.(^&1r3)))n do.
n=: n+1
end.
_1 + n=:n+1
)</lang>
 
<lang j>stateySquare=:2 conew'mthPower'
And, here is an example of using that generator to accomplish this task:
stateyCube=:3 conew'mthPower'</lang>
 
Here is a generator for squares which are not cubes:
<lang j> 20 }.next__g"0 i.30 [ g=: conew'generator'
 
<lang j>coclass 'uncubicalSquares'
N=:0
next=:3 :0"0
while.(-:<.)3%:*:n=.N do.N=:N+1 end.N=:N+1
*:n
)</lang>
 
And here is an example of its use:
 
<lang j> 20next__g }i.10 [ next__g"0 i.3020 [ g=: conew 'generatoruncubicalSquares'
529 576 625 676 784 841 900 961 1024 1089</lang>
 
That said, here is a more natural approach, for J.
 
<lang j>mthPower=:1 :'^&m@i.'
squares=: 2 mthPower
cubes=:3 mthPower
uncubicalSquares=: squares -. cubes</lang>
 
The downside of this approach is that it is computing independent sequences. And for the "uncubicalSquares" verb, it is removing some elements from that sequence. So you must estimate how many values to generate. However, this can be made transparent to the user with a simplistic estimator:
 
<lang j>uncubicalSquares =: {. squares@<.@p.~&3 1.1 -. cubes</lang>
 
Example use:
 
<lang j>20 }. uncubicalSquares 30
529 576 625 676 784 841 900 961 1024 1089</lang>
 
smoutput next__g i.10 [ next__g i.20 [ g=:conew 'uncubicalSquares'
 
=={{header|PicoLisp}}==
6,962

edits