Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Simple Maths helper program with between 1 and 3 inputs
String askUser(String question) {
process.write(question);
return process.readLine();
}
Float? askUserForNumber(String question) => parseFloat(askUser(question));
void printResult(Float(Float, Float=, Float=) operation, Float x, Float? y, Float? z) {
Float result;
if (exists y) {
if (exists z) {
result = operation(x, y, z);
} else {
result = operation(x, y);
}
} else {
result = operation(x);
}
print("Result: ``result``");
}
shared void run() {
function multiply(Float a, Float b = 1.0, Float c = 1.0) => a * b * c;
function add(Float a, Float b = 0.0, Float c = 0.0) => a + b + c;
function askForOptionalNumber(String question, Boolean askUser) {
if (askUser) {
return askUserForNumber(question);
} else {
return null;
}
}
value multiplication = 0;
value addition = 1;
value option = askUserForNumber("Enter ``multiplication`` for multiplication, ``addition`` for addition: ");
value x = askUserForNumber("Enter x: ");
value y = askForOptionalNumber("Enter y (optional): ", x exists);
Float? z = askForOptionalNumber("Enter z (optional): ", y exists);
assert(is Float option, is Float x,
option == multiplication || option == addition);
printResult(option == multiplication then multiply else add, x, y, z);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment