Mad Libs: Difference between revisions
m
→{{header|Wren}}: Minor tidy
(Added Commodore BASIC.) |
m (→{{header|Wren}}: Minor tidy) |
||
(10 intermediate revisions by 10 users not shown) | |||
Line 32:
{{trans|Python}}
<
found a <noun>. <name> decided to take it home.’
Line 44:
print("\nThe story becomes:\n\n"story)
madlibs(template)</
{{out}}
Line 65:
The fun of Mad Libs is not knowing the story ahead of time, so the program reads the story template from a text file. The name of the text file is given as a command line argument.
<
procedure Madlib is
Line 96:
Ada.Text_IO.Put_Line(Text.Element(I));
end loop;
end Madlib;</
It uses an auxiliary package String_Helper for simple string functions;
<
package String_Helper is
Line 124:
function Get_Vector(Filename: String) return Vector;
end String_Helper;</
Here is the implementation of String_Helper:
<
package body String_Helper is
Line 178:
end Get_Vector;
end String_Helper;</
A sample run (with the story template in t.txt):
Line 193:
=={{header|Aime}}==
<
data b;
list l;
Line 225:
}
l.ucall(o_, 0, "\n");</
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<
# gets the story template from the file f. The template terminates with #
Line 356:
story( stand in )
)</
{{out}}
<pre>
Line 373:
----
<syntaxhighlight lang="applescript">
set theNoun to the text returned of (display dialog "What is your noun?" default answer "")
Line 383:
display dialog thePerson & " went for a walk in the park. " & theGender & " found a " & theNoun & ". " & thePerson & " decided to take it home."
</syntaxhighlight>
=={{header|Applesoft BASIC}}==
<syntaxhighlight lang="gwbasic"> 100 DIM L$(100),W$(50),T$(50)
110 LET M$ = CHR$ (13)
120 FOR L = 1 TO 1E9
130 READ L$(L)
140 IF LEN (L$(L)) THEN NEXT L
150 FOR I = 1 TO L
160 LET M = 0
170 LET N$(0) = ""
180 FOR J = 1 TO LEN (L$(I))
190 LET C$ = MID$ (L$(I),J,1)
200 IF C$ = "<" AND NOT M THEN M = 1:C$ = "":N$(M) = ""
210 IF C$ = ">" AND M THEN GOSUB 300:M = 0:C$ = W$(Z)
220 LET N$(M) = N$(M) + C$
230 NEXT J
240 LET L$(I) = N$(0)
250 NEXT I
260 FOR I = 1 TO L
270 PRINT M$L$(I);
280 NEXT
290 END
300 FOR Z = 0 TO T
310 IF T$(Z) = N$(M) THEN RETURN
320 NEXT Z
330 LET T = Z
340 LET T$(Z) = N$(M)
350 PRINT M$"ENTER A "T$(Z);
360 INPUT "? ";W$(Z)
370 RETURN
380 DATA "<NAME> WENT FOR A WALK IN THE PARK. <HE OR SHE>"
390 DATA "FOUND A <NOUN>. <NAME> DECIDED TO TAKE IT HOME."
990 DATA</syntaxhighlight>
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">story: strip input "Enter a story: "
vars: unique map match story {/\|([^\|]+)\|/} 'v -> replace v "|" ""
i: 0
while [i < size vars].import [
let vars\[i] input ~"Enter value for <|vars\[i]|>: "
i: i + 1
]
print ~story</syntaxhighlight>
{{out}}
<pre>Enter a story: |name| went for a walk in the park. |heOrShe| found a |noun|. |name| decided to take it home.
Enter value for <name>: Johnny
Enter value for <heOrShe>: He
Enter value for <noun>: chameleon
Johnny went for a walk in the park. He found a chameleon. Johnny decided to take it home.</pre>
=={{header|AutoHotkey}}==
Like some other examples, this prompts the user for a text file template.<br/>AutoHotkey is interestingly well suited for this task...
<
If ErrorLevel
ExitApp ; the user canceled the file selection
Line 399 ⟶ 452:
StringReplace, contents, contents, %match%, %repl%, All
}
MsgBox % contents</
{{out|Sample Output}}
<pre>Han Solo went for a walk in the park. She
Line 405 ⟶ 458:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f MAD_LIBS.AWK
BEGIN {
Line 440 ⟶ 493:
exit(0)
}
</syntaxhighlight>
{{out}}
<pre>
Line 458 ⟶ 511:
=={{header|BASIC256}}==
<syntaxhighlight lang="basic256">
cadena = "<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
k = instr(cadena, "<")
Line 474 ⟶ 527:
print : print "La historia final: " : print cadena
end
</syntaxhighlight>
=={{header|C}}==
Dealing with c strings can be quite annoying. This solution implements a dynamic string type with simple functionality which makes the actual madlibs logic a bit clearer. A quicker solution would probably circumvent the copying and moving over characters in the string by utilizing a different data structure that could make use of pointers to input data. This would reduce copying, and require less memory, and allocations for.
<syntaxhighlight lang="c">
#include <stdio.h>
#include <stdlib.h>
Line 625 ⟶ 678:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
Line 638 ⟶ 691:
=={{header|C++}}==
<
#include <string>
using namespace std;
Line 685 ⟶ 738:
return 0;
}</
=={{header|C sharp}}==
<
using System.Linq;
using System.Text;
Line 758 ⟶ 811:
}
}
</syntaxhighlight>
=={{header|Clojure}}==
<
(:require [clojure.string :as str]))
Line 820 ⟶ 873:
; While Bob Dylan walk, strange man
; appears and gave Bob Dylan a Nobel prize.
</syntaxhighlight>
=={{header|Commodore BASIC}}==
This program in its current form is specific to the Commodore 64 memory map and utilizes the RAM untouched by BASIC beginning at $C000 (49152). This can be adjusted for other Commodore computers by changing the memory starting address which is variable <code>tb</code> in line 15. It also assumes using disk drive device 8 to read the input file.
<syntaxhighlight lang="gwbasic">10 rem mad lib for rosetta code
15 dim bf$(100),wd$(50),tg$(50):tb=49152
20 print chr$(147);chr$(14);"Mad Lib Processor":print
25 gosub 1000
Line 853 ⟶ 907:
230 return
250 print chr$(147):print "Processing...":print
255 m=
260 t$=bf$(i)
265 for c=1 to len(t$):ch$=mid$(t$,c,1)
Line 860 ⟶ 914:
280 m=m-1:return
300 rem insert cr for word wrap
310 pt=
320 if peek(pt)=32 then gosub 350:if(ll+sz>39) then poke pt,13:ll=-1:sz=0
325 if peek(pt)=13 then ll=-1
Line 873 ⟶ 927:
400 rem output memory buffer
401 ln=0:print chr$(147);
410 for i=
420 if c=13 then ln=ln+1
425 print chr$(c);
Line 910 ⟶ 964:
2105 print:print er;"- ";en$;" at .:";et$;" .:";es$
2110 print:print "Press a key.":gosub 500
2115 return</
'''Input File'''
Line 994 ⟶ 1,048:
ready.
█</pre>
=={{header|D}}==
{{trans|Ruby}}
<
void main() {
Line 1,017 ⟶ 1,070:
writeln("\nThe story becomes:\n", story);
}</
{{out}}
<pre>Enter a story template, terminated by an empty line:
Line 1,032 ⟶ 1,085:
=={{header|Erlang}}==
<
-compile(export_all).
Line 1,084 ⟶ 1,137:
lists:foldl(fun ([M],D) ->
dict:store(M,"",D)
end, Dict, Matches).</
This version can be called via either madlib:main() or madlib:main(File) to read from standard_in or from a file.
Line 1,091 ⟶ 1,144:
{{out}}
<
Please name a <noun>: banana
Please name a <name>: Jack
Line 1,097 ⟶ 1,150:
Jack went for a walk in the park. She
found a banana. Jack decided to take it home.ok
69> </
=={{header|Factor}}==
<
IN: rosetta-code.mad-libs
Line 1,121 ⟶ 1,174:
get-mad-lib dup find-replacements replacements nl print ;
MAIN: mad-libs</
{{out}}
<pre>
Line 1,174 ⟶ 1,227:
written on it. Joseph the lucky decided to take it home.
<syntaxhighlight lang="fortran">
MODULE MADLIB !Messing with COMMON is less convenient.
INTEGER MSG,KBD,INF !I/O unit numbers.
Line 1,414 ⟶ 1,467:
CALL WRITESTORY(66)
END
</syntaxhighlight>
=={{header|FreeBASIC}}==
<
Dim As String con, cadena
cadena = "<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
Line 1,435 ⟶ 1,488:
Print Chr(10) & "La historia final: "
Print cadena & Chr(10)
</syntaxhighlight>
=={{header|Go}}==
Variance: The fun of Mad Libs is not knowing the story ahead of time, so instead of asking the player to enter the story template, my program asks the player to enter the file name of a story template (with contents presumably unknown to the player.)
<
import (
Line 1,495 ⟶ 1,548:
return m[p]
}))
}</
Sample run:
<pre>
Line 1,511 ⟶ 1,564:
=={{header|Haskell}}==
This will read a template story via stdin with no arguments, or read from a file if given as an argument.
<
import System.Environment (getArgs)
Line 1,562 ⟶ 1,615:
nlines_ <- parseText nlines M.empty
putStrLn ""
putStrLn nlines_</
=={{header|Icon}} and {{header|Unicon}}==
This just runs with the sample. It would be much more fun with a database of randomly selected story templates.
<
ml := "<name> went for a walk in the park. There <he or she> _
found a <noun>. <name> decided to take it home." # sample
Line 1,581 ⟶ 1,634:
story := replace(story,v,read())
write("\nYour MadLib follows:\n",story)
end</
{{libheader|Icon Programming Library}}
Line 1,599 ⟶ 1,652:
Implementation:
<
madlib=:3 :0
Line 1,612 ⟶ 1,665:
end.
t
)</
Example use:
<
Please enter the story template
See http://rosettacode.org/wiki/Mad_Libs for details
Line 1,627 ⟶ 1,680:
Jill went for a walk in the park. she
found a rock. Jill decided to take it home.
</syntaxhighlight>
=={{header|Java}}==
I tried to fix this... but this is my first one.
<
public class MadLibs {
Line 1,655 ⟶ 1,708:
}
}
</syntaxhighlight>
=={{header|Julia}}==
Line 1,661 ⟶ 1,714:
{{trans|Python}}
<
function madlibs(template)
println("The story template is:\n", template)
Line 1,679 ⟶ 1,732:
"""
madlibs(template)</
{{out}}
Line 1,696 ⟶ 1,749:
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 1,717 ⟶ 1,770:
}
println("\n$story")
}</
{{out}}
Line 1,736 ⟶ 1,789:
=={{header|Liberty BASIC}}==
<
k = instr(temp$,"<")
while k
Line 1,749 ⟶ 1,802:
print temp$
wait
</syntaxhighlight>
=={{header|Lua}}==
<syntaxhighlight lang="lua">print("Enter a multi-line story (finish with blank line):")
dict, story, line = {}, "", io.read()
while #line>0 do story=story..line.."\n" line=io.read() end
story = story:gsub("(%<.-%>)", function(what)
if dict[what] then return dict[what] end
io.write("Please enter a " .. what .. ": ")
dict[what] = io.read()
return dict[what]
end)
print("\n"..story)</syntaxhighlight>
{{out}}
<pre>Enter a multi-line story (finish with blank line):
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
Please enter a <name>: Mark
Please enter a <he or she>: He
Please enter a <noun>: fork
Mark went for a walk in the park. He
found a fork. Mark decided to take it home.</pre>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Like some other examples, this prompts the user for a filename for a story template rather than reading the story in from user input.
<
InputString["Enter the filename of the story template:"]];
answers =
Line 1,763 ⟶ 1,839:
" " <> StringTrim[#, "<" | ">"] <> ":"] &,
Union[StringCases[text, RegularExpression["<[^>]+>"]]]];
Print[StringReplace[text, Normal[answers]]];</
{{out}}
<pre>George went for a walk in the park. he
found a car. George decided to take it home.</pre>
=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">def madlib(template)
// loop through and find/remove all of the replacements
replacements = {}
ind = 0
while ind < len(template)
// check if we have found a replacement to perform
if template[ind] = "<"
// get the name of the replacement and add it to the list
// if we haven't already encountered it
ind += 1
replace_name = ""
while template[ind] != ">"
replace_name += template[ind]
ind += 1
end while
if not replace_name in replacements
replacements.append(replace_name)
end if
ind += 1
else
ind += 1
end if
end while
// prompt the user for replacement values
replacement_values = {}
for phrase in replacements
replacement_values.append(input("enter " + phrase + ": "))
end for
println
// make replacements and output the story
ind = 0
while ind < len(template)
// check if we have found a replacement to perform
if template[ind] = "<"
// get the name of the replacement
ind += 1
replace_name = ""
while template[ind] != ">"
replace_name += template[ind]
ind += 1
end while
// output the replacement
print replacement_values[replacements[replace_name]]
ind += 1
else
print template[ind]
ind += 1
end if
end while
end madlib
madlib("<name> went for a walk in the park. <he or she> " + \
"found a <noun>. <name> decided to take it home.")</syntaxhighlight>
=={{header|Nim}}==
{{trans|Python}}
<
#let templ = readLineFromStdin "Enter your story: "
Line 1,785 ⟶ 1,920:
for f,v in zip(fields, values).items:
story = story.replace(f, v)
echo "\nThe story becomes:\n\n", story</
Sample run:
<pre>The story template is:
Line 1,801 ⟶ 1,936:
=={{header|Oforth}}==
<
| story i word |
Line 1,811 ⟶ 1,946:
]
"Your story :" . story println ;</
=={{header|Pascal}}==
Line 1,823 ⟶ 1,958:
So, no stories involving < symbols, please.
<syntaxhighlight lang="pascal">
Program Madlib; Uses DOS, crt; {See, for example, https://en.wikipedia.org/wiki/Mad_Libs}
{Reads the lines of a story but which also contain <xxx> sequences. For each value of xxx,
Line 1,929 ⟶ 2,064:
for i:=1 to StoryLines do Roll(Story[i]); {Write the amended story.}
END.
</syntaxhighlight>
Example run:
C:\Nicky\Pascal\FILEME~1>MADLIB.EXE
Line 1,940 ⟶ 2,075:
=={{header|Perl}}==
Use the name of the file with a story as the parameter to the programme.
<
use warnings;
use strict;
Line 1,958 ⟶ 2,093:
$story =~ s/<(.*?)>/$blanks{$1}/g;
print $story;</
=={{header|Phix}}==
Set mlfile to the name of a suitable file, if you have one, otherwise it uses the default story.
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- file i/o, prompt_string</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">mlfile</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- eg story.txt</span>
<span style="color: #000000;">mltxt</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">mlfile</span><span style="color: #0000FF;">)?</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">read_lines</span><span style="color: #0000FF;">(</span><span style="color: #000000;">mlfile</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">):</span><span style="color: #008000;">"""
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
"""</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">strings</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{},</span> <span style="color: #000000;">replacements</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">startpos</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">endpos</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">startpos</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'<'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">mltxt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">endpos</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">startpos</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">endpos</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'>'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">mltxt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">startpos</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">endpos</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #008000;">"missing >"</span> <span style="color: #7060A8;">abort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">mltxt</span><span style="color: #0000FF;">[</span><span style="color: #000000;">startpos</span><span style="color: #0000FF;">..</span><span style="color: #000000;">endpos</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">strings</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">strings</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">strings</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">replacements</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">replacements</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">prompt_string</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Enter replacement for %s:"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">})))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">substitute_all</span><span style="color: #0000FF;">(</span><span style="color: #000000;">mltxt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">strings</span><span style="color: #0000FF;">,</span><span style="color: #000000;">replacements</span><span style="color: #0000FF;">))</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,990 ⟶ 2,128:
found a Rosetta Code Task. Pete decided to take it home.
</pre>
Removing all file i/o and prompts to make it pwa/p2js compatible, same final output:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">mltxt</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
"""</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">strings</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"<name>"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"<he or she>"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"<noun>"</span><span style="color: #0000FF;">},</span>
<span style="color: #000000;">replacements</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"Pete"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"He"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Rosetta Code Task"</span><span style="color: #0000FF;">}</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">startpos</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">endpos</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">startpos</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'<'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">mltxt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">endpos</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">startpos</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">endpos</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'>'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">mltxt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">startpos</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #000000;">endpos</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"missing >"</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">mltxt</span><span style="color: #0000FF;">[</span><span style="color: #000000;">startpos</span><span style="color: #0000FF;">..</span><span style="color: #000000;">endpos</span><span style="color: #0000FF;">]</span>
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">strings</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">substitute_all</span><span style="color: #0000FF;">(</span><span style="color: #000000;">mltxt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">strings</span><span style="color: #0000FF;">,</span><span style="color: #000000;">replacements</span><span style="color: #0000FF;">))</span>
<!--</syntaxhighlight>-->
=={{header|Phixmonti}}==
<
true
while
Line 2,010 ⟶ 2,169:
endwhile
print
</syntaxhighlight>
=={{header|Picat}}==
<syntaxhighlight lang="picat">import util.
go =>
Story = read_story(),
println("Fill in the proper values:"),
nl,
Map = get_info(get_tags(Story)) ,
println("\nHere is the story:\n"),
println(replace_tags(Story,Map)),
nl.
read_story() = Story =>
println("Write the story template with <tag> for the tags and finish with an empty line."),
nl,
Story1 = read_line(),
while (Line = read_line(), Line != "")
Story1 := Story1 ++ " " ++ Line
end,
Story = Story1.
%
% Get the tags between <...>.
%
get_tags(S) = Tags =>
Len = S.length,
StartPos = [P: {C,P} in zip(S,1..Len), C = '<'],
EndPos = [P: {C,P} in zip(S,1..Len), C = '>'],
Tags = [slice(S,Start,End) : {Start,End} in zip(StartPos,EndPos)].remove_dups().
%
% Get the tag info from user and return a map
%
get_info(Tags) = Map =>
Map = new_map(),
foreach(Tag in Tags)
printf("%w: ", Tag),
Map.put(Tag,readln())
end.
% Replace all the <tags> with user values.
replace_tags(S,Map) = S =>
foreach(Tag=Value in Map)
S := replace_string(T,Tag,Value)
end.
% Picat's replace/3 does not handle substrings well,
% so we roll our own...
replace_string(List,Old,New) = Res =>
Res = copy_term(List),
while (find(Res,Old,_,_))
once(append(Before,Old,After,Res)),
Res := Before ++ New ++ After
end.</syntaxhighlight>
{{out}}
<pre>Write the story template with <tag> for the tags and finish with an empty line.
<name> went for a walk in the park.
<he or she> found <a or an> <noun>.
<name> decided to take it home.
Fill in the proper values:
<name>: Snow White
<he or she>: She
<a or an>: an
<noun>: apple
Here is the story:
Snow White went for a walk in the park. She found an apple. Snow White decided to take it home.</pre>
=={{header|PicoLisp}}==
This function extends the syntax a bit to be able to express different words with the same description, the syntax is <name:description>, if the description is omitted the name is used instead, keeping backwards compatibility with the syntax used in the task description:
<
(setq Template (split (chop Template) "<" ">"))
(let (Reps () Text ())
Line 2,030 ⟶ 2,263:
(prinl (need 30 '-))
(prinl (flip Text)) ) )
</syntaxhighlight>
This runs the example:
Line 2,070 ⟶ 2,303:
=={{header|Pike}}==
this solution uses readline to make editing more convenient.
<
Stdio.Readline readln = Stdio.Readline();
Line 2,153 ⟶ 2,386:
else add_line(input);
}
}</
{{out}}
Line 2,190 ⟶ 2,423:
=={{header|PL/I}}==
{{incorrect|PL/I|This seems to hard code the replaceable symbols instead of taking them from the story.}}
<
Mad_Libs: procedure options (main);
declare (line, left, right) character (100) varying;
Line 2,260 ⟶ 2,493:
end split;
end Mad_Libs;</
<pre>
Please type a name:
Line 2,271 ⟶ 2,504:
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function New-MadLibs
{
Line 2,337 ⟶ 2,570:
"`n{0} went for a walk in the park. {1} found a {2}. {0} decided to take it home.`n" -f $Name, $pronoun, $Item
}
</syntaxhighlight>
Command line input:
<syntaxhighlight lang="powershell">
New-MadLibs -Name hank -Male -Item shank
</syntaxhighlight>
{{Out}}
<pre>
Line 2,347 ⟶ 2,580:
</pre>
Prompt for input:
<syntaxhighlight lang="powershell">
New-MadLibs
</syntaxhighlight>
{{Out}}
<pre>
Line 2,366 ⟶ 2,599:
</pre>
Command line input using splatting:
<syntaxhighlight lang="powershell">
$paramLists = @(@{Name='mary'; Female=$true; Item="little lamb"},
@{Name='hank'; Male=$true; Item="shank"},
Line 2,375 ⟶ 2,608:
New-MadLibs @paramList
}
</syntaxhighlight>
{{Out}}
<pre>
Line 2,385 ⟶ 2,618:
Foo went for a walk in the park. He found a bar. Foo decided to take it home.
</pre>
=={{header|PureBasic}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="purebasic">
If OpenConsole()
cadena$ = "<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
k = FindString(cadena$, "<")
PrintN("La historia: ")
Print(cadena$ + Chr(10))
While k
reemplaza$ = Mid(cadena$, k, FindString(cadena$, ">") - k + 1)
Print(Chr(10) + "What should replace " + reemplaza$ + " ")
con$ = Input ()
While k
cadena$ = Left(cadena$, k-1) + con$ + Mid(cadena$, k + Len(reemplaza$))
k = FindString(cadena$, reemplaza$, k)
Wend
k = FindString(cadena$, "<")
Wend
PrintN(Chr(10) + "La historia final: ")
PrintN(cadena$)
Input()
CloseConsole()
EndIf
End
</syntaxhighlight>
{{out}}
<pre>
Igual que la entrada de FreeBASIC.
</pre>
=={{header|Python}}==
<
# Optional Python 2.x compatibility
Line 2,407 ⟶ 2,673:
print('\nThe story becomes:\n\n' + story)
madlibs(template)</
{{out}}
Line 2,424 ⟶ 2,690:
=={{header|Racket}}==
Instead of writing the story in the console, it reads from a file given by the player, this is mainly to keep surprise about the final text
<
(with-input-from-file file
(lambda ()
Line 2,451 ⟶ 2,717:
(string-replace mad-story (car change) (cdr change)))))
(play-mad-libs)</
{{out}} with the story from this page
Line 2,465 ⟶ 2,731:
{{works with|rakudo|2015-09-18}}
Some explanation: <tt>S:g[...] = ...</tt> is a global substitution that returns its result. <tt>%</tt> is an anonymous state variable in which we cache any results of a prompt using the <tt>//=</tt> operator, which assigns only if the left side is undefined. <tt>slurp</tt> reads an entire file from STDIN or as named in the argument list.
<syntaxhighlight lang="raku"
Sample run:
<pre>$ madlibs walk
Line 2,475 ⟶ 2,741:
=={{header|REBOL}}==
<
t: {<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home.}
view layout [a: area wrap t btn "Done" [x: a/text unview]]
parse x [any [to "<" copy b thru ">" (append w: [] b)] to end]
foreach i unique w [replace/all x i ask join i ": "] alert x
</syntaxhighlight>
=={{header|Red}}==
While the REBOL GUI version above also works in Red with minor changes, here is a text-only version.
<
while [not empty? line: input] [append phrase rejoin ["^/" line]]
words: parse phrase [collect [any [to "<" copy b thru ">" keep (b)]]]
foreach w unique words [replace/all phrase w ask rejoin [w ": "]]
print phrase</
{{out}}
Remarkably (with Red 0.6.4 for Windows built 5-Aug-2020/18:58:49+02:00), replacements made in original phrase are dynamically reflected in the display of the phrase entered. Hence first stage of execution yields:
Line 2,505 ⟶ 2,771:
=={{header|REXX}}==
<
parse arg iFID . /*allow user to specify the input file.*/
if iFID=='' | iFID=="," then iFID="MAD_LIBS.TXT" /*Not specified? Then use the default.*/
Line 2,539 ⟶ 2,805:
say copies('═', 79) /*display a final (output) fence. */
say /*stick a fork in it, we're all done. */</
Some older REXXes don't have a '''changestr''' BIF, so one is included here ──► [[CHANGESTR.REX]].
<br><br>
Line 2,559 ⟶ 2,825:
=={{header|Ring}}==
<
temp="<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
k = substr(temp,"<")
Line 2,573 ⟶ 2,839:
end
see temp + nl
</syntaxhighlight>
=={{header|Ruby}}==
<
story = ""
until (line = gets).chomp.empty?
Line 2,588 ⟶ 2,854:
puts
puts story</
Example
Line 2,603 ⟶ 2,869:
=={{header|Run BASIC}}==
<
k = instr(temp$,"<")
while k
Line 2,615 ⟶ 2,881:
wend
print temp$
wait</
{{out}}
<pre>
Line 2,626 ⟶ 2,892:
=={{header|Rust}}==
{{libheader|regex}}
<
use regex::Regex;
Line 2,668 ⟶ 2,934:
}
println!("Resulting story:\n\n{}", template);
}</
{{out}}
<pre>
Line 2,692 ⟶ 2,958:
=={{header|Scala}}==
<
val input = "<name> went for a walk in the park. <he or she>\nfound a <noun>. <name> decided to take it home."
println(input)
Line 2,705 ⟶ 2,971:
println
println(output)
}</
{{out}}
<pre><name> went for a walk in the park. <he or she>
Line 2,718 ⟶ 2,984:
=={{header|Seed7}}==
<
const proc: main is func
Line 2,748 ⟶ 3,014:
writeln("The story becomes:");
write(story);
end func;</
{{out}}
Line 2,767 ⟶ 3,033:
=={{header|Sidef}}==
{{trans|Perl}}
<
var blanks = Hash.new;
Line 2,779 ⟶ 3,045:
}
print story.gsub(/<(.*?)>/, {|s1| blanks{s1} });</
=={{header|tbas}}==
<
LET LHS = POS(TXT$, LHS$, AFTER)
IF LHS = 0 THEN
Line 2,830 ⟶ 3,096:
END WHILE
PRINT STORY$</
=={{header|Tcl}}==
<
# Read the template...
Line 2,855 ⟶ 3,121:
puts [string repeat "-" 70]
puts -nonewline [string map $mapping $content]
puts [string repeat "-" 70]</
Sample session:
<pre>
Line 2,874 ⟶ 3,140:
=={{header|VBScript}}==
<syntaxhighlight lang="vb">Function mad_libs(s)
Do
If InStr(1,s,"<") <> 0 Then
parse_string = Mid(s,start_position,end_position-start_position)
WScript.StdOut.Write parse_string & "? "
input_string = WScript.StdIn.ReadLine
s = Replace(s,"<" & parse_string & ">",input_string)
Else
Exit Do
End If
Loop
mad_libs = s
End Function
WScript.StdOut.Write mad_libs("<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home.")
WScript.StdOut.WriteLine</syntaxhighlight>
{{Out}}
<pre>F:\>cscript /nologo mad_libs.vbs
name? babe
he or she? she
noun? cat
babe went for a walk in the park. she found a cat. babe decided to take it home.</pre>
=={{header|Visual Basic .NET}}==
Line 2,908 ⟶ 3,170:
"\<" can be used to escape a "<" outside of a template (the escape is not recognized within a template), and "\>" can be used to escape a ">" inside of a template. Templates can span lines. A possible improvement from a UX standpoint is to check for template validity before beginning to request for substitutions; currently, unclosed templates are only found when they are encountered in the replacement process.
<
Module Program
Line 2,976 ⟶ 3,238:
Console.Write(result)
End Sub
End Module</
{{out|note=for sample input}}
Line 3,019 ⟶ 3,281:
{{libheader|Wren-pattern}}
{{libheader|Wren-seq}}
<
import "./pattern" for Pattern
import "./seq" for Lst
System.print("Please enter a multi-line story template terminated by a blank line:\n")
Line 3,041 ⟶ 3,303:
story = story.replace(blank, repl)
}
System.print("\n%(story)")</
{{out}}
Line 3,060 ⟶ 3,322:
=={{header|zkl}}==
<
do{ line=ask("Story: "); story.write(line,"\n") }while(line);
while(re.search(story,True)){
Line 3,068 ⟶ 3,330:
}
println("-----------------");
story.text.print();</
{{out}}
<pre>
|