Skip to content

Instantly share code, notes, and snippets.

@renatoathaydes
Created August 25, 2014 20:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save renatoathaydes/54e50f29abad7fda2a27 to your computer and use it in GitHub Desktop.
Save renatoathaydes/54e50f29abad7fda2a27 to your computer and use it in GitHub Desktop.
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