Search code examples
rubyperlfunctional-programmingflip-flop

Is there a functional programming concept equivalent to the flip-flop operator in Perl or Ruby?


Ruby (and Perl) has a concept of the flip flop:

file = File.open("ordinal")
while file.gets
  print if ($_ =~ /third/) .. ($_ =~ /fifth/)
end

which given a list of ordinals, such as

first
second
third
fourth
fifth
sixth

would start printing when it reached "third" and stop when it reached "fifth":

third
fourth
fifth

Is there a functional programming concept analogous to this, or would this normally be described in terms of takewhiles? I'm not asking about a particular language, just what term you'd use to describe it.


Solution

  • In a functional language such as haskell, you would pass in the flip and flop conditions as predicates, and filter an input list based on it. For example, the following is a definition of flipflop in haskell (don't worry about the implementation if you don't know haskell - the key part is how it is used):

    flipflop flip flop = 
      uncurry (++) . second (take 1) . break flop . dropWhile (not . flip)
    

    This is how it can be used:

    > flipflop (== 3) (== 5) [1..10]
    [3,4,5]
    

    It is an example of making an effectively new language construct just by using higher ordered function.

    I don't know if there is a special name for that construct in functional languages.