I am trying to use a reduce function to &-connect multiple sequel expressions. However in the beginning I'd have the need for a natural element / identity element Sequel-expression. i.e. an expression that can be &-connected without changing the meaning of the query. I tried just using nil, but that does not seem to work. Is there such a thing?^^
Imagine the following
def reduce(buffer, array, &func)
return buffer if array.empty?
if buffer.nil? # I basically want to get rid of this
reduce(array[0], array[1..-1], &func)
else
reduce(func.call(buffer, array[0]), array[1..-1], &func)
end
end
# to be able to call:
reduce(NATURAL_ELEMENT, array_of_expressions) { |first, second| first & second }
When calling Sequel.expr(nil)
I get a #<Sequel::SQL::Wrapper @value=>nil>
but I don't know exactly what effect that has. Is this what I am looking for?
What you want is a universal set, i.e. a set containing all possible elements. This is the identity for set intersections. If you use
Sequel.expr(nil)
, you'll have the equivalent of an empty set.I'm not aware of any universal set (or other identity object) in Sequel, but you could try to implement one. Here's an example (using the
Singleton
module for good measure):Now you can use this in set intersection operations. The type of the elements is irrelevant, so it works fine for
SQL
objects, as well.If you want to, you can also implement the other set operations for the universal set.
This, however, has the downside that it is not commutative. If you try the inverse:
it will throw an error. This is a limitation in the available coercion constructs in Ruby. (Currently you can only overload operators commutatively for numbers.)