Κυριακή 6 Νοεμβρίου 2022

Generators in M2000

Genertators can be formed with various ways. The easy way is to make them using a lambda function, with some closures (the closures are variables local in lambda)

m=lambda k=1 (span) -> {
=k : k+=span
}
Dim a(10)<<m(3)
Print a()

We can make easy copies like z=m where z has own k with the last state in m. We don't need Yield to send back data because all the job done in each run (the state hold in closures). We can use ? as Print.

m=lambda k=1 (n)->{
if n<1 then =1: exit
m=k: k++:=n/(k*lambda(n-1))
}
z=m
Dim a(1 to 1000)<<m(5)
For i=1 to 1000 step 500: Print str$(a(i),"##0.000000"): Next
For i=991 to 1000: Print str$(a(i),"##0.000000000"): Next
For i=1 to 10 : ? str$(z(5),"##0.000000"),str$(a(i),"##0.000000"), i :Next

This is the main example. Edit A then paste the code then press Esc and just give A and enter to run.



form 60, 32
pen 14
back { cls 0,0}
cls 0 ,0
double
pen 15 {report 2, "Generators in M2000"}
normal
cls 5, 2
report "Example 1 - call back"
function generator(&yield()) {
call yield("Welcome")
call yield("to")
call yield("M2000 interpreter")
}
function yieldthere (new a$) {
print @(tab*2),a$
}
call generator(lazy$(&yieldthere()))


report "Example 2 - call back in a loop"
function generator2(&yield(), numbers) {
for n=1 to numbers
if n mod 2 =1 then call yield(n)
next
}
m=(,)
function yieldthere2 (new a) {
append m, (a,)
}
call generator2(lazy$(&yieldthere2()), 30)
print m
Center=2 // use 6 for center proportional character display
oldTab=tab
print $(Center, width ), m#str$(", "),$(0, oldTab)
print Len(m)
report "Example 3 - fill arrays, random span"
odd=lambda n=0 (w) -> {
if n mod w = 1 then push n
push "ok"
n++
}
function generator3() {
stack new {
try stream
if not islet then exit else drop
if not empty then =number else loop
}
}
leave=random(2, 5)
print "from 1 leave ";leave-1
dim a(10)<<generator3()<<odd(leave)
print a()
report "Example 4 - change offset but using same span as Example 3"
nn=1+leave
function yield4 {
if nn mod leave = 1 then push nn
push "ok"
nn++
}
link weak lazy$(&yield4()) to odd1()
dim a(10)<<generator3()<<odd1()
print a()
nn=100
dim a(10)<<generator3()<<odd1()
print a()
report "Example 5 using odd1() from Example 4"
function generator4(&count, &v) {
if count<1 then =false: exit
stack new {
try stream
if not islet then exit else drop
if not empty then v=number : count-- else loop
}
=true
}
nn=1000
many=30
manyleft=many
retval=0
while generator4(&manyleft, &retval )<<odd1()
print $(3), format$("{0::-5} ({1::-2})",retval, many-manyleft),$(0),
end while
print
Rem {
cls , row-1
keyboard "edit "+module.name$+chr$(13)
}






Δεν υπάρχουν σχόλια:

Δημοσίευση σχολίου

You can feel free to write any suggestion, or idea on the subject.