Flip-flop (programming)

In computer programming, a flip-flop is a seldom-used syntactic construct which allows a boolean to flip from true to false when a first condition is met, and back to false when a second condition is met. It is not simply equivalent to "if A and not B"; the expression has persistent state and is true even if A is no longer true, as long as at some point in the past A was true and B has always been false. The syntax is available in the programming languages Perl[1] and Ruby.[2] Similar logic is available in sed and awk.[1]

Example

The following Ruby code prints the numbers 4 through 6:

(1..10).each do |x|
  puts x if (x == 4 .. x == 6)
end

The first instance of ".." is the range operator, which produces the enumeration of integers 1 through 10. The second ".." is the flip-flop operator. Note that the number 5 is printed even though both "x == 4" and "x== 6" are false. This is because the expression remembers that "x == 4" was true on a previous iteration, and that "x == 6" had at that point never been true.

References

  1. 1 2 "Perl operators and precedence". Retrieved 2016-10-21.
  2. Nithin Bekal (2014-11-21). "Flip Flop Operator in Ruby".


This article is issued from Wikipedia - version of the 10/21/2016. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.