Search⌘ K
AI Features

Challenge: Perform the Calculation

Explore solving a challenge to design a function that accepts multiple Calculation structs in D, processes operations like addition, subtraction, multiplication, and division, and returns an array of results. This lesson helps you practice handling variable parameters and working with structured data types.

We'll cover the following...

Problem statement

Assume that the following enum is already defined:

enum Operation { add, subtract, multiply, divide }

Also, assume that there is a struct that represents the calculation of an operation and its two operands:

struct Calculation {
    Operation op;
    double first;
    double second;
}
svg viewer

For example, the object Calculation(Operation.divide, 7.7, 8.8) would represent the division of 7.7 by 8.8.

Design a function that receives an unspecified number of these struct objects, calculates the result of each Calculation, and then returns all of the results as a slice of type double[].

Sample input

For example, it should be possible to call the function, as in the following code:

void main() {
    writeln( 
      calculate(Calculation(Operation.add, 1.1, 2.2), 
        Calculation(Operation.subtract, 3.3, 4.4), 
        Calculation(Operation.multiply, 5.5, 6.6), 
        Calculation(Operation.divide, 7.7, 8.8)));
}

Sample output

The output of the code should be similar to the following:

[3.3, -1.1, 36.3, 0.875]

Challenge

This problem is designed for you to practice, so try to solve it on your own first. If you get stuck, you can always refer to the explanation and solution provided in the next lesson. Good luck!

D
import std.stdio;
enum Operation { add, subtract, multiply, divide }
struct Calculation {
Operation op;
double first;
double second;
}
double[] calculate(/* .. */) {
// ...
}
void mainFunction() {
writeln(calculate(Calculation(Operation.add, 1.1, 2.2),
Calculation(Operation.subtract, 3.3, 4.4),
Calculation(Operation.multiply, 5.5, 6.6),
Calculation(Operation.divide, 7.7, 8.8)));
}