Mad Libs: Difference between revisions

Content added Content deleted
(Simpler regex in D entry)
(Rewritten D entry, fits better the Task)
Line 212: Line 212:


=={{header|D}}==
=={{header|D}}==
{{trans|Python}}
{{trans|Ruby}}
<lang d>import std.stdio, std.regex, std.array, std.algorithm,
<lang d>import std.stdio, std.regex, std.algorithm, std.string, std.array;
std.string, std.range;


void main() {
void main() {
writeln("Enter a story template, terminated by an empty line:");
auto story = "<name> went for a walk in the park. <he or she>
string story;
found a <noun>. <name> decided to take it home.";
while (true) {
writeln("The story template is:\n", story);
auto line = stdin.readln().strip();
writeln("\nInput a comma-separated list of words "
if (line.empty) break;
"to replace the following items:");
story ~= line ~ "\n";
}

auto re = regex("<.+?>", "g");
auto re = regex("<.+?>", "g");
auto fields = story.match(re).map!q{a.hit}().array().sort().uniq();
auto fields = story.match(re).map!q{a.hit}().array().sort().uniq();
writef(" %s: ", fields.join(","));
foreach (field; fields) {
writef("Enter a value for '%s': ", field[1 .. $ - 1]);
const values = std.string.split(stdin.readln().strip(), ",");
story = story.replace(field, stdin.readln().strip());
foreach (f, v; zip(fields, values))
}
story = story.replace(f, v);

writeln("\nThe story becomes:\n", story);
writeln("\nThe story becomes:\n", story);
}</lang>
}</lang>
{{out}}
{{out}}
<pre>The story template is:
<pre>Enter a story template, terminated by an empty line:
<name> went for a walk in the park. <he or she>
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
found a <noun>. <name> decided to take it home.


Enter a value for 'he or she': She
Input a comma-separated list of words to replace the following items:
<he or she>,<name>,<noun>: She,Monica,cockerel
Enter a value for 'name': Monica
Enter a value for 'noun': cockerel


The story becomes:
The story becomes: