Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a programming language with the following features exist?

Is there a language which will support the following concept or is there a pattern to achieve something similar with existing one?

Concept

I want to define a Rectangle with the following properties: Length, Height, Area, Perimeter; where Area = Length * Height and Perimeter = (2 * Length) + (2 * Height).

Given the statement above, if I want to create a Rectangle by giving it a Length and a Height, it should of course automatically fill out the rest of the properties.

However, it should go further and automatically allow you to create a Rectangle with any two properties (say Height and Perimeter) because that is also mathematically enough to create the same Rectangle.

Example

To help explain the idea, take this example:

//Declaration
Rectangle
{
    Height, Length, Area, Perimeter;

    Area = Height * Length;
    Perimeter = (2 * Length) + (2 * Height);
}

//Usage
main()
{
    var rectangleA = new Rectangle(Height, Length);
    var rectangleB = new Rectangle(Height, Area);

    Assert(rectangleA == rectangleB);
}

Notice how I didn't need to define constructors for Rectangle. Notice I did not need specify the specific logic needed if a Rectangle was created using Height and Area.

Edit: Should be rectangle and not a square for a proper example.

like image 869
hatcyl Avatar asked Jul 21 '16 03:07

hatcyl


1 Answers

What you are looking for is a language with an integrated computer algebra system. It has to be able to resolve equations with respect to different variables.

While it would be possible to implement something like this, I doubt that it would make sense because in many cases there will be either no solution or multiple solutions.

Even your simple example will not work if only area and perimeter are given because there will usually be two solutions. (I assume that your class actually represents a rectangle and not a square, otherwise you should not have separate variables for length and height.)

Example:

Input: area = 2, perimeter = 6
Solution 1: length = 2, height = 1
Solution 2: length = 1, height = 2

Another remark not really related to your question: Your class obviously contains redundant member variables. This is a bad thing for various reasons, the most important being the possibility of inconsistencies. Unless you have very strict performance constraints, you should store only two of them, say length and width, and provide methods to calculate the others when needed.

like image 180
Frank Puffer Avatar answered Sep 20 '22 03:09

Frank Puffer