3 ms·
Thats cool. Here's the somewhat equivalent in C++: struct square { int x; }; struct rectangle { int x; int y;
by pfultz2 12y ago
Thats cool. Here's the somewhat equivalent in C++:
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.
- codygman 12y agoCool, it's always good to see other languages approaches (especially when idiomatic) to try out their way of thinking. > 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.
- he_the_great 12y agoAnd the same thing in D: 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)]
- codygman 12y agoI've been debating whether or not to choose C++ or D to learn as my "when performance really matters" language. I'm still going to learn Rust, but I'm very interested in D. I also like that it has a pure keyword ;)