RosettaCodeData/Task/Menu/D/menu.d

36 lines
1.1 KiB
D
Raw Permalink Normal View History

2013-10-27 22:24:23 +00:00
import std.stdio, std.conv, std.string, std.array, std.typecons;
2013-04-10 21:29:02 -07:00
string menuSelect(in string[] entries) {
2013-10-27 22:24:23 +00:00
static Nullable!(int, -1) validChoice(in string input,
in int nEntries)
pure nothrow {
2013-04-10 21:29:02 -07:00
try {
2013-10-27 22:24:23 +00:00
immutable n = input.to!int;
return typeof(return)((n >= 0 && n <= nEntries) ? n : -1);
} catch (Exception e) // Very generic
return typeof(return)(-1); // Not valid.
2013-04-10 21:29:02 -07:00
}
if (entries.empty)
return "";
while (true) {
2013-10-27 22:24:23 +00:00
"Choose one:".writeln;
foreach (immutable i, const entry; entries)
2013-04-10 21:29:02 -07:00
writefln(" %d) %s", i, entry);
2013-10-27 22:24:23 +00:00
"> ".write;
immutable input = readln.chomp;
immutable choice = validChoice(input, entries.length - 1);
if (choice.isNull)
"Wrong choice.".writeln;
2013-04-10 21:29:02 -07:00
else
2013-10-27 22:24:23 +00:00
return entries[choice]; // We have a valid choice.
2013-04-10 21:29:02 -07:00
}
}
void main() {
immutable items = ["fee fie", "huff and puff",
"mirror mirror", "tick tock"];
2013-10-27 22:24:23 +00:00
writeln("You chose '", items.menuSelect, "'.");
2013-04-10 21:29:02 -07:00
}