Continued fraction/Arithmetic/Construct from rational number: Difference between revisions

(→‎{{header|XPL0}}: Added zkl)
Line 1,126:
13/11 [1;5,2] 1.181818181818180E+000
22/7 [3;7] 3.142857142857140E+000
</pre>
 
=={{header|zkl}}==
Two iterators; one light weight, one heavy weight.
 
Light weight, explicit state:
<lang zkl>fcn r2cf(nom,dnom){ // -->Walker (iterator)
Walker.tweak(fcn(_,state){
nom,dnom:=state;
if(dnom==0) return(Void.Stop);
n,d:=nom.divr(dnom);
state.clear(dnom,d);
n
}.fp1(List(nom,dnom)))
}</lang>
Heavy weight, implicit state:
<lang zkl>fcn r2cf2(nom,dnom){ // -->Generator (heavy weight Walker)
Utils.Generator(fcn(nom,dnom){
while(dnom){
n,d:=nom.divr(dnom); nom,dnom=dnom,d;
vm.yield(n);
}
Void.Stop;
},nom,dnom)
}</lang>
Both of the above return an iterator so they function the same:
<lang zkl>foreach nom,dnom in (T(T(1,2), T(3,1), T(23,8), T(13,11), T(22,7),
T(14142,10000), T(141421,100000), T(1414214,1000000),
T(14142136,10000000))){
r2cf(nom,dnom).walk(25).println(); // print up to 25 numbers
}</lang>
{{out}}
<pre>
L(0,2)
L(3)
L(2,1,7)
L(1,5,2)
L(3,7)
L(1,2,2,2,2,2,1,1,29)
L(1,2,2,2,2,2,2,3,1,1,3,1,7,2)
L(1,2,2,2,2,2,2,2,3,6,1,2,1,12)
L(1,2,2,2,2,2,2,2,2,2,6,1,2,4,1,1,2)
</pre>
Anonymous user