Flip-flop (programming)

From HandWiki

In computer programming, a flip-flop is a seldom-used syntactic construct which allows a boolean to flip from false to true when a first condition is met and then back to false when a second condition is met. The syntax is available in the programming languages Perl[1] and Ruby.[2] Similar logic is available in sed and awk.[1]

A flip-flop with first condition A and second condition B is not equivalent to "if A and not B", as the former 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.

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, otherwise known as the flip floperator.[3] 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.

Pitfalls

The flip-flop operator needs to store its current state. There is no way for the programmer to explicitly define where this state is stored and what its lifetime is. The lifetime makes a difference when the same code is used by several threads, or in recursive functions. These concurrent accesses to the state of the flip-flop operator can lead to undefined behavior, or at least surprising results, depending on the programming language. For example, in Perl each flip-flop operator has its own state, shared among all the threads,[4] the other programming languages do the same.

To work around this limitation, the flip-flop operator would have to be modeled as an abstract data type, parameterized with:

  • a predicate that tells whether to switch the flip-flop on,
  • a predicate that tells whether to switch the flip-flop off.

This flip-flop data type would provide a function that queries and updates its state at the same time. This function gets the actual data on which the switching predicates depend and passes that data to the two predicates, if necessary.

Due to this inherent complexity, only few programming languages have adopted the flip-flop operator.

References