Depends on functional language. How about this?
ff_gen =
lambda{ |first, *conditions|
flipflop = false
condition = first
lambda{ |v|
if condition && condition[v]
condition = conditions.shift
flipflop = !flipflop
true
else
flipflop
end
}
}
ff = ff_gen[lambda{|v| v == 3}, lambda{|v| v == 5}, lambda{|v| v == 7}, lambda{|v| v == 11}]
puts (0..20).select{ |i| ff[i] }.inspect # => [3, 4, 5, 7, 8, 9, 10, 11]
Added: Of course, Ruby is not a pure functional language, so I decided to rewrite it in Erlang:
#!/usr/bin/env escript
flipflop(E, {[H|T] = Conditions, FlipFlop}) ->
case H(E) of
true ->
{true, {T, not FlipFlop}};
false ->
{FlipFlop, {Conditions, FlipFlop}}
end;
flipflop(_, {[], FlipFlop}) ->
{FlipFlop, {[], FlipFlop}}.
flipflop_init(Conditions) ->
{[], {Conditions, false}}.
main([]) ->
{L, _} =
lists:foldl(
fun(E, {L2, FFState}) ->
case flipflop(E, FFState) of
{true, FFState2} ->
{[E|L2], FFState2};
{false, FFState2} ->
{L2, FFState2}
end
end,
flipflop_init([
fun(E) -> E == 3 end,
fun(E) -> E == 5 end,
fun(E) -> E == 7 end,
fun(E) -> E == 11 end
]),
lists:seq(0,20)
),
io:format("~p~n", [lists:reverse(L)]),
ok.
Note: In fact, classic flip-flop should work like dropwhile(!first) -> takewhile(!second), so Ruby's flip-flop is ad hoc one (compare with flip-flop in electronics).