I currently try to port a piece of code from Ruby to Python to do a bit algorithm research. I have no experience in Ruby and don't know how to handle the 'yield' keyword.
The code is for a Myers diff algorithm and fully described in this blog
This is the code snippet I don't understand:
while x > prev_x and y > prev_y
yield x - 1, y - 1, x, y
x, y = x - 1, y - 1
end
Is there a way to approximate this in Python?
Almost identically. Though the semantics of Python's and Ruby's
yieldis somewhat different, in this case they coincide almost exactly.Ruby's
yieldinvokes a block that is passed into the function, giving it its parameters.Python's
yieldmakes the function a generator, and generates one output from it.Both of them only make sense in context of a function, so just your
whileloop is too short a context to use it. But let's take something like it as a simplified example, in Ruby:This function accepts a block with one parameter, then generates numbers up to that number along with their double and executes that block with those parameters:
As blocks are basically the same thing as callback functions, it is equivalent to this Python:
On the other hand, Python's
yieldcreates a generator - a function that returns a function that can produce values on demand:The most natural way to consume a generator is via a
forloop:In Ruby, the closest literal translation is
Enumerator:and the most natural way to consume an
Enumeratoris usingeach(which is what Rubyists prefer overfor):But, as I said, even though they do something slightly different, the original Ruby above (with
yield) is surprisingly similar to the original Python above (withyield). The way they are consumed is slightly different, but appropriate to each language's idiom.In your case, if you leave
yieldexactly as it is in your Python, the line that consumes it changes from Ruby'sto Python's
You can read more at Python yield vs Ruby yield.
Note that the most natural way to write this loop is not
whilein either language (I'd userangein Python andtimesin Ruby), but I wanted to have code that looks similar for both languages, for comparison.