Why doesn't this simple Lua coroutine work? - multithreading

I have a very simple little piece of Lua code, which I wrote while teaching myself how coroutines work.
I was fine until I got to coroutine.wrap, the spec states:
coroutine.wrap (f)
Creates a new coroutine, with body f.
f must be a Lua function. Returns a
function that resumes the coroutine
each time it is called. Any arguments
passed to the function behave as the
extra arguments to resume. Returns the
same values returned by resume, except
the first boolean. In case of error,
propagates the error.
However this code:
Enumeration = {}
Enumeration.Create = function(generator)
return coroutine.wrap(generator, coroutine.yield)
end
local function TestEnumerator(yield)
yield(1) --ERROR HERE
yield(2)
yield(3)
end
local enumerator = Enumeration.Create(TestEnumerator)
local first = enumerator()
local second = enumerator()
local third = enumerator()
print (first, second, third)
Complains that yield is nil (on the line I have marked above). As I understand it, yield should be the second argument passed into coroutine.wrap, so where am I going wrong?
Really obvious solution, thanks to the answer below
Enumeration.Create = function(generator)
local iter = coroutine.wrap(generator, coroutine.yield)
return function()
return iter(coroutine.yield)
end
end

This is not how coroutine.wrap works. You have to pass coroutine.yield in the first call to enumerator.

Related

Binary Search algorithm random array

I don't understand why the recursive function always gives me zero result, even if I put values inside the array.
it seems that size (a) == 0
recursive function binarySearch_R (a, value) result (bsresult)
real, intent(in) :: a(6), value
integer :: bsresult, mid
mid = size(a)/2 + 1
if (size(a) == 0) then
bsresult = 0 ! not found
else if (a(mid) > value) then
bsresult= binarySearch_R(a(:mid-1), value)
else if (a(mid) < value) then
bsresult = binarySearch_R(a(mid+1:), value)
if (bsresult /= 0) then
bsresult = mid + bsresult
end if
else
bsresult = mid ! SUCCESS!!
end if
end function binarySearch_R
program hji
read*, a
read*, value
print*, binarySearch_R
end program hji
Chapter 1: The dangers of implicit typing
The first thing I strongly recommend you do is to include the line
implicit none
after the program line. This will suppress implicit typing, and the resulting errors will give you some useful insight into what is happening.
If you did that, you'd get an error message:
$ gfortran -o binsearch binsearch.f90
binsearch.f90:23:12:
read*, a
1
Error: Symbol ‘a’ at (1) has no IMPLICIT type
binsearch.f90:27:25:
print*,binarySearch_R
1
Error: Symbol ‘binarysearch_r’ at (1) has no IMPLICIT type
binsearch.f90:24:16:
read*, value
1
Error: Symbol ‘value’ at (1) has no IMPLICIT type
It doesn't matter that a, value, and binarySearch_R were defined in the function. As the function is not part of the program block, the program doesn't know what these are.
With implicit typing active, it simply assumed that all three are simple real variables. (The type depends on the first letter of the variable name, i through n are integer, everything else is real)
Because this implicit typing can so easily hide coding errors, it's strongly, strongly suggested to always switch it off.
Which also means that we have to declare the variables a and value in the program:
program hji
implicit none
real :: a(6), value
...
end program hji
Chapter 2: How to introduce a function to the program?
So how does the program get access to the function? There are four ways:
The best way: Use a module
module mod_binsearch
implicit none
contains
recursive function binarySearch_R (a, value) result (bsresult)
...
end function binarySearch_R
end module mod_binsearch
program hji
use mod_binsearch
implicit none
real :: a(6), value
...
end program hji
Note that the use statement has to be before the implicit none.
This method leaves the function separate, but callable.
It automatically checks that the parameters (that's something we'll be coming to in a bit) are correct.
Have the function contained in the program.
Between the final line of code of the program and the end program statement, add the keyword contains, followed by the function code (everything from recursive function ... to end function ...).
This is the quick-and-dirty method. You have to be careful with this method as the function will automatically have access to the program's variables unless there's a new variable with that name declared inside the function.
The convoluted way: Interfaces
Create an interface block in the declaration section of your program's source code,
and repeat the interface information in there.
This still allows the compiler to check whether the function is invoked correctly, but it's up to you to ensure that this interface block is correct and matches the actual implementation.
The really, really ugly way: Declare it like a variable, invoke it like a function.
Please don't do that.
Chapter 3: Calling a function
When you call a function, you have to use the parentheses and give it all the parameters that it expects. In your case, you need to type
print *, binarySearch_r(a, value)
Chapter 4: Dynamic arrays as dummy parameters
In the successive recursive calls to the function, the array gets smaller and smaller.
But the dummy parameter is always the same size (6). Not only will this interfere with your algorithm, but this can also lead to dangerously undefined memory access.
Fortunately, specially for intent(in) dummy parameters, you can use dynamic arrays:
recursive function binarySearch_R(a, value)
real, intent(in) :: a(:), value
The single colon tells the compiler to expect a one-dimensional array, but not the length of it. Since you're already using size(a), it should automatically work.
Too long for a comment, but not an answer (and to any Fortran experts reading this, yes, there are one or two places where I gloss over some details because I think they are unimportant at this stage) ...
The way the code is written does not allow the compiler to help you. As far as the compiler is concerned there is no connection between the function and the program. As far as the program is concerned a is, because you haven't told the compiler otherwise, assumed to be a real scalar value. The a in the program is not the same thing as the a in the function - there is no connection between the function and the program.
The same is true for value.
The same is true for binarysearch_r - and if you don't believe this delete the function definition from the source code and recompile the program.
So, what must you do to fix the code ?
First step: modify your source code so that it looks like this:
program hji
... program code goes here ...
contains
recursive function binarySearch_R (a, value) result (bsresult)
... function code goes here ...
end function binarySearch_R
end program hji
This first step allows the compiler to see the connection between the program and the function.
Second step: insert the line implicit none immediately after the line program hji. This second step allows the compiler to spot any errors you make with the types (real or integer, etc) and ranks (scalar, array, etc) of the variables you declare.
Third step: recompile and start dealing with the errors the compiler identifies. One of them will be that you do not pass the arguments to the function so the line
print*, binarySearch_R
in the program will have to change to
print*, binarySearch_R(a, value)

Why does this recursive addition return none

This is a weird one print return 9 and then it prints 1 , also i checked debugger in pycharm and the (stuff) keeps counting down for some reason
def repeater(stuff):
if stuff != 9:
stuff += 1
print(stuff)
repeater(stuff)
return stuff
print(repeater(0))
When you call repeater(stuff), you're not passing the variable stuff, you're passing a copy of the variable stuff. When you say stuff += 1, you're not modifying the stuff you called the function with, you're modifying a copy of it. That change isn't reflected in the original when you exit the function.
Then, when the function exits, you don't do anything with the returned value of stuff - which is, again, copied out of the function in reverse. Python does let you call the function without using its return value, but it looks like your intent here is to apply the returned value of repeater(stuff) to stuff.
To accomplish that, simply change the line
repeater(stuff)
to
stuff = repeater(stuff)
The reason for that additional 1 that is coming in the end is that repeater(stuff) is returning the value of stuff which is being received by your print statement i.e. print(repeater(0)). When all the recursive calls return back, none of the values are stored/used but the very first call that was made by print(repeater(0)) obtains a value of 1 because repeater(stuff) returns the value of stuff which would be 1 after stuff += 1 during the first call.
You can read more about how recursion works for more clarity.

Confused about Node js two brackets function

I'm trying to understand the recursive function in NodeJS, but I'm still confused about the following code and output:
var firstf = function () {
var counter = 0;
return function () {
console.log("counter = " + counter);
return counter += 1;
}
};
var add = firstf();
add();//output 0
add();//output 1
add();//output 2
firstf()();//output 0
firstf()();//output 0
firstf()();//output 0
I can understand three add() functions output 0,1,2, but I could not understand why three firstf()() output 0,0,0. what does two ()() mean please?
Also one follow up question: for this line: var add = firstf();
the variable add will represents the return function as:
function () {
console.log("counter = " + counter);
return counter += 1;
}
Ok, the question is that how could this function see the variable counter, since counter in upper level, not defined in this inner function.
There is no recursion here. Recursion is where a function calls itself. This is called a closure. Because the inner function contains references to variables in the outer function's scope. Here's a good article on closures. From that article:
A closure is the combination of a function bundled together (enclosed)
with references to its surrounding state (the lexical environment).
In
other words, a closure gives you access to an outer function’s scope
from an inner function. In JavaScript, closures are created every time
a function is created, at function creation time. To use a closure,
define a function inside another function and expose it.
To expose a
function, return it or pass it to another function. The inner function
will have access to the variables in the outer function scope, even
after the outer function has returned.
Now, let's diagnose exactly what is happening with firstf()().
First that calls firstf(). That initializes the internal counter to 0 and returns a new function.
Then, the second () executes that returned function which returns the value of counter which is 0 and increments it.
Then, you call firstf()() again. That initializes a new counter variable to 0 and returns a new function. Then, the second () calls that function and returns the new counter value of 0 and then increments it.
So, that explains why successive calls to firstf()() just keep returning 0. You keep making a new function and a new counter variable each time.
When you do var add = firstf(); and then call add(), you are storing the returned function and then calling the same function over and over again. That will keep using the same internal counter variable and thus you will see the returned value going up as that internal counter variable is incremented each time.
what does two ()() mean please?
Each () attempts to execute a function. In firstf()(), the first () executes firstf() and gets the function that it returns. The second () then executes that returned function and gets whatever it returns (the counter value).

Receiving function as another function´s parameter

Let´s say I have 2 functions like these ones:
def list(n):
l=[x for x in range(n)]
return l
def square(l):
l=list(map(lambda x:x**2,l))
print(l)
The first one makes a list from all numbers in a given range which is "n" and the second one receives a list as a parameter and returns the squared values of this list.
However when I write:
square(list(20))
it raises the error "map object cannot be interpreted as an integer" and whenever I erase one of the functions above and run the other one it runs perfectly and I have no idea what mistake I made.
You redefined the standard function list()! Rename it to my_list() and clean the code accordingly.
As a side note, your function list() is doing exactly what list(range(n)) would do. Why do you need it at all? In fact, for most purposes (including your example), range(n) alone is sufficient.
Finally, you do not pass a function as a parameter. You pass the value generated by another function. It is not the same.

Is this recursive?

Second attempt here, I just wanted to know if this is considered a recursive function.
The purpose of the function is to take a string and
if the the first element is equal to the last element
then append the last element to a list and return nothing,
else call istelf and pass the same string from index [1]
finally append the first element to the list
I know that error checking needs to be done on the if statement. However I am only doing this to try and get my head around recursion...Struggling to be honest.
Also I would never write a program like this if it where anything but trivial I just wanted to check if my understanding is correct so far.
def parse(theList):
theList.reverse()
parsedString = ''.join(theList)
return parsedString
def recursiveMessage(theString):
lastElement = theString[len(theString) - 1]
if theString[0] == lastElement:
buildString.append(theString[0])
return None
else:
recursiveMessage(theString[1::])
buildString.append(theString[0])
toPrint = "Hello Everyone!"
buildString = []
recursiveMessage(toPrint)
print(parse(buildString))
Thanks again.
Is this recursive?
If at any point in a function's execution it calls itself, then it is consider recursive. This happens in your example, so recursiveMessage is indeed recursive.
so which is quicker recursion or iteration?
Recursion is usually much slower and consumes more space due to a new stack frame having to be created on the call stack each recursive call. If you know your recursive function will need to be run many times, iteration is the best route.
As an interesting side note, many compilers actually optimize a recursive function by rolling it out into a loop anyways.

Resources