Hmm, not easy to explain in a simple and concise way
Say I have a grid, with n
columns and m
lines, which I want to fill with data from an Enumerable
(whatever contents).
Of course, each entry in the Enumerable
will correspond to a line in the grid, but I now need to define which data should appear in which column.
To do this, I put the definition of each column in an array, including at least a label
and a Proc
to extract the data.
I then come to the following definitions in (pseudo)code:
class Column(T)
def initialize(@label : String, @extract : T -> ???)
end
end
class Line(T)
include Enumerable(???)
def initialize(@grid : Grid(T), @source : T)
end
def each
yield ...
end
end
class Grid(T)
include Enumerable(Line(T))
def initialize(@sources : Enumerable(T))
@columns = {} of String => Column(T)
end
def each
yield ...
end
def add_column(label, &extractor)
@columns[label] = extractor
end
end
Say I have the following Enumerable as sources : data = {'a' => [1, "A", 3.14], 'b' => [2, "Z", 2.718]}
So I define the grid with :
g = Grid.new(data)
g.add_column("col 1") {|k, v| k}
g.add_column("col 2") {|k, v| v[2]}
and printing the grid would give :
a 3.14
b 2.718
In the code above, I have represented the type of data I am looking for with ???
In this example, the type ???
is Char | Float64 | Int32 | String
while T
is Tuple(Char, Array(Float64 | Int32 | String))
but with for example, a source data of [['a', 3.14], ['b', 2.718]]
, it would have been only Char | Float64
So, my question is, in this case, is it possible to derive an union of simple types from any type of Enumerable(T)
to avoid to have to define manually an alias in the application source code with the drawbacks I mentioned in my first post?
Hope it’s more clear ?
Thanks