by pfultz2 · 12y ago · 0 comments
struct square
{
int x;
};
struct rectangle
{
int x;
int y;
};
boost::variant<square, rectangle> to_shape(int x, int y)
{
if (x == y) return square(x);
else return rectangle(x, y);
}
std::vector<std::pair<int, int>> unknowns = {
{5, 4},
{3, 2},
{4, 4}
};
auto shapes = unknowns | boost::adaptors::transformed(boost::fusion::make_fused(to_shape));
Of course, the structs are not polymoprhic and can't be printed out. I just left that out because it requires a little more code to do that. Obviously with haskell its much less code.I would very much be interested in the dependently typed version.
struct Square
{
int sideLength;
}
struct Rectangle {
int length;
int width;
}
import std.variant;
alias Shape = Algebraic!(Square, Rectangle);
import std.typecons;
auto to_shape(Tuple!(int, int) shape) pure nothrow
{
if (shape[0] == shape[1]) return Shape(Square(shape[0]));
else return Shape(Rectangle(shape.expand));
}
void main() {
auto unknowns = [
tuple(5, 4),
tuple(3, 2),
tuple(4, 4)
];
import std.stdio;
import std.algorithm;
writeln(unknowns.map!(to_shape));
}
[Rectangle(5, 4), Rectangle(3, 2), Square(4)]> I would very much be interested in the dependently typed version.
I'll try to get to it later today, I'm pretty busy until then.