Trying to emulate list comprehensions syntax I came with this syntax that resembles haskell list comprehensions (by having several guards separated by ,
and allowing zero guards):
> (1..24).comp { |x| [x, x.even?, x > 6] }
=> [8, 10, 12, 14, 16, 18, 20, 22, 24]
> [nil, nil, 1, 2, 3, 4, 5].comp { |x| [x, x != 4] }
=> [nil, nil, 1, 2, 3, 5]
> [nil, nil, 1, 2, 3, 4, 5].comp { |x| [x] }
=> [nil, nil, 1, 2, 3, 4, 5]
This solution may not be the fastest but doesn't destroy nil
values and is similar to list comprehensions syntax.
The implementation is:
module Enumerable
def comp(&block)
return self if block.nil?
self.map(&block).select do |x, *cond|
cond.all?
end.map { |x, *rest| x }
end
end
The block receives each element of the Enumerable
and returns an Array
, where the first element is the value, and the rest are the boolean guards (if any).