Mad Libs: Difference between revisions

18,821 bytes added ,  5 months ago
m
(Added Commodore BASIC.)
m (→‎{{header|Wren}}: Minor tidy)
 
(10 intermediate revisions by 10 users not shown)
Line 32:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">V template = ‘<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.’
 
Line 44:
print("\nThe story becomes:\n\n"story)
 
madlibs(template)</langsyntaxhighlight>
 
{{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.
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Ada.Command_Line, String_Helper;
 
procedure Madlib is
Line 96:
Ada.Text_IO.Put_Line(Text.Element(I));
end loop;
end Madlib;</langsyntaxhighlight>
 
It uses an auxiliary package String_Helper for simple string functions;
 
<langsyntaxhighlight Adalang="ada">with Ada.Containers.Indefinite_Vectors;
 
package String_Helper is
Line 124:
function Get_Vector(Filename: String) return Vector;
 
end String_Helper;</langsyntaxhighlight>
 
Here is the implementation of String_Helper:
 
<langsyntaxhighlight Adalang="ada">with Ada.Strings.Fixed, Ada.Text_IO;
 
package body String_Helper is
Line 178:
end Get_Vector;
 
end String_Helper;</langsyntaxhighlight>
 
A sample run (with the story template in t.txt):
Line 193:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">file f;
data b;
list l;
Line 225:
}
 
l.ucall(o_, 0, "\n");</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<langsyntaxhighlight lang="algol68"># Mad Libs style story generation #
 
# gets the story template from the file f. The template terminates with #
Line 356:
story( stand in )
 
)</langsyntaxhighlight>
{{out}}
<pre>
Line 373:
 
----
<syntaxhighlight lang="applescript">
<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>
</lang>
 
=={{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...
<langsyntaxhighlight AHKlang="ahk">FileSelectFile, filename, , %A_ScriptDir%, Select a Mad Libs template, *.txt
If ErrorLevel
ExitApp ; the user canceled the file selection
Line 399 ⟶ 452:
StringReplace, contents, contents, %match%, %repl%, All
}
MsgBox % contents</langsyntaxhighlight>
{{out|Sample Output}}
<pre>Han Solo went for a walk in the park. She
Line 405 ⟶ 458:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f MAD_LIBS.AWK
BEGIN {
Line 440 ⟶ 493:
exit(0)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 458 ⟶ 511:
 
=={{header|BASIC256}}==
<syntaxhighlight lang="basic256">
<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>
</lang>
 
 
=={{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">
<lang c>
#include <stdio.h>
#include <stdlib.h>
Line 625 ⟶ 678:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 638 ⟶ 691:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <string>
using namespace std;
Line 685 ⟶ 738:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Text;
Line 758 ⟶ 811:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(ns magic.rosetta
(:require [clojure.string :as str]))
 
Line 820 ⟶ 873:
; While Bob Dylan walk, strange man
; appears and gave Bob Dylan a Nobel prize.
</syntaxhighlight>
</lang>
 
=={{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.
<lang gwbasic>10 rem mad lib for rosetta code
 
15 dim bf$(100),wd$(50),tg$(50)
<syntaxhighlight lang="gwbasic">10 rem mad lib for rosetta code
18 poke 53281,15:poke 53280,12:poke 646,11
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=49152tb:os=0:ns=0:for i=1 to bp-1
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=49152tb:sz=0:ll=0
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=49152tb to m:c=peek(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</langsyntaxhighlight>
 
'''Input File'''
Line 994 ⟶ 1,048:
ready.
&#9608;</pre>
 
 
=={{header|D}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="d">import std.stdio, std.regex, std.algorithm, std.string, std.array;
 
void main() {
Line 1,017 ⟶ 1,070:
 
writeln("\nThe story becomes:\n", story);
}</langsyntaxhighlight>
{{out}}
<pre>Enter a story template, terminated by an empty line:
Line 1,032 ⟶ 1,085:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(madlib).
-compile(export_all).
 
Line 1,084 ⟶ 1,137:
lists:foldl(fun ([M],D) ->
dict:store(M,"",D)
end, Dict, Matches).</langsyntaxhighlight>
 
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}}
<langsyntaxhighlight lang="erlang">68> madlib:main("test.mad").
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> </langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting io kernel make regexp sequences sets splitting ;
IN: rosetta-code.mad-libs
 
Line 1,121 ⟶ 1,174:
get-mad-lib dup find-replacements replacements nl print ;
 
MAIN: mad-libs</langsyntaxhighlight>
{{out}}
<pre>
Line 1,174 ⟶ 1,227:
written on it. Joseph the lucky decided to take it home.
 
<syntaxhighlight lang="fortran">
<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>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="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>
</lang>
 
=={{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.)
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,495 ⟶ 1,548:
return m[p]
}))
}</langsyntaxhighlight>
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.
<langsyntaxhighlight Haskelllang="haskell">import System.IO (stdout, hFlush)
 
import System.Environment (getArgs)
Line 1,562 ⟶ 1,615:
nlines_ <- parseText nlines M.empty
putStrLn ""
putStrLn nlines_</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight Iconlang="icon">procedure main()
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</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 1,599 ⟶ 1,652:
Implementation:
 
<langsyntaxhighlight Jlang="j">require 'general/misc/prompt regex'
 
madlib=:3 :0
Line 1,612 ⟶ 1,665:
end.
t
)</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight Jlang="j"> madlib''
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>
</lang>
 
=={{header|Java}}==
I tried to fix this... but this is my first one.
 
<langsyntaxhighlight Javalang="java">import java.util.*;
 
public class MadLibs {
Line 1,655 ⟶ 1,708:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
Line 1,661 ⟶ 1,714:
{{trans|Python}}
 
<langsyntaxhighlight lang="julia">
function madlibs(template)
println("The story template is:\n", template)
Line 1,679 ⟶ 1,732:
"""
 
madlibs(template)</langsyntaxhighlight>
 
{{out}}
Line 1,696 ⟶ 1,749:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun main(args: Array<String>) {
Line 1,717 ⟶ 1,770:
}
println("\n$story")
}</langsyntaxhighlight>
 
{{out}}
Line 1,736 ⟶ 1,789:
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">temp$="<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
k = instr(temp$,"<")
while k
Line 1,749 ⟶ 1,802:
print temp$
wait
</syntaxhighlight>
</lang>
 
=={{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.
<langsyntaxhighlight Mathematicalang="mathematica">text = Import[
InputString["Enter the filename of the story template:"]];
answers =
Line 1,763 ⟶ 1,839:
" " <> StringTrim[#, "<" | ">"] <> ":"] &,
Union[StringCases[text, RegularExpression["<[^>]+>"]]]];
Print[StringReplace[text, Normal[answers]]];</langsyntaxhighlight>
{{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}}
<langsyntaxhighlight lang="nim">import rdstdin, re, algorithm, sequtils, strutils
 
#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</langsyntaxhighlight>
Sample run:
<pre>The story template is:
Line 1,801 ⟶ 1,936:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: madlibs
| story i word |
Line 1,811 ⟶ 1,946:
]
"Your story :" . story println ;</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 1,823 ⟶ 1,958:
 
So, no stories involving < symbols, please.
<syntaxhighlight lang="pascal">
<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>
</lang>
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.
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
use warnings;
use strict;
Line 1,958 ⟶ 2,093:
 
$story =~ s/<(.*?)>/$blanks{$1}/g;
print $story;</langsyntaxhighlight>
 
=={{header|Phix}}==
Set mlfile to the name of a suitable file, if you have one, otherwise it uses the default story.
<!--<syntaxhighlight lang="phix">-->
<lang Phix>string mlfile = "", -- eg story.txt
<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>
mltxt = iff(length(mlfile)?join(read_lines(mlfile),"\n"):"""
<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>
<name> went for a walk in the park. <he or she>
<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;">"""
found a <noun>. <name> decided to take it home.
&lt;name&gt; went for a walk in the park. &lt;he or she&gt;
""")
found a &lt;noun&gt;. &lt;name&gt; decided to take it home.
 
"""</span><span style="color: #0000FF;">)</span>
sequence strings = {}, replacements = {}
integer startpos, endpos=1
<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>
while 1 do
<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>
startpos = find('<',mltxt,endpos)
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
if startpos=0 then exit end if
<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;">'&lt;'</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>
endpos = find('>',mltxt,startpos)
<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>
if endpos=0 then ?"missing >" abort(0) end if
<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;">'&gt;'</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>
string s = mltxt[startpos..endpos]
<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 &gt;"</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>
if not find(s,strings) then
<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>
strings = append(strings,s)
<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>
replacements = append(replacements,prompt_string(sprintf("Enter replacement for %s:",{s})))
<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>
end if
<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>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
puts(1,substitute_all(mltxt,strings,replacements))</lang>
<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;">"""
&lt;name&gt; went for a walk in the park. &lt;he or she&gt;
found a &lt;noun&gt;. &lt;name&gt; 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;">"&lt;name&gt;"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"&lt;he or she&gt;"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"&lt;noun&gt;"</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;">'&lt;'</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;">'&gt;'</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 &gt;"</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}}==
<langsyntaxhighlight Phixmontilang="phixmonti">"<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
true
while
Line 2,010 ⟶ 2,169:
endwhile
print
</syntaxhighlight>
</lang>
 
=={{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:
<langsyntaxhighlight PicoLisplang="picolisp">(de madlib (Template)
(setq Template (split (chop Template) "<" ">"))
(let (Reps () Text ())
Line 2,030 ⟶ 2,263:
(prinl (need 30 '-))
(prinl (flip Text)) ) )
</syntaxhighlight>
</lang>
 
This runs the example:
Line 2,070 ⟶ 2,303:
=={{header|Pike}}==
this solution uses readline to make editing more convenient.
<langsyntaxhighlight Pikelang="pike">#!/usr/bin/pike
Stdio.Readline readln = Stdio.Readline();
Line 2,153 ⟶ 2,386:
else add_line(input);
}
}</langsyntaxhighlight>
 
{{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.}}
<langsyntaxhighlight PLlang="pl/Ii">(stringrange, stringsize): /* 2 Nov. 2013 */
Mad_Libs: procedure options (main);
declare (line, left, right) character (100) varying;
Line 2,260 ⟶ 2,493:
end split;
 
end Mad_Libs;</langsyntaxhighlight>
<pre>
Please type a name:
Line 2,271 ⟶ 2,504:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<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>
</lang>
Command line input:
<syntaxhighlight lang="powershell">
<lang PowerShell>
New-MadLibs -Name hank -Male -Item shank
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,347 ⟶ 2,580:
</pre>
Prompt for input:
<syntaxhighlight lang="powershell">
<lang PowerShell>
New-MadLibs
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,366 ⟶ 2,599:
</pre>
Command line input using splatting:
<syntaxhighlight lang="powershell">
<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>
</lang>
{{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}}==
<langsyntaxhighlight lang="python">import re
 
# Optional Python 2.x compatibility
Line 2,407 ⟶ 2,673:
print('\nThe story becomes:\n\n' + story)
 
madlibs(template)</langsyntaxhighlight>
 
{{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
<langsyntaxhighlight Racketlang="racket">(define (get-mad-libs file)
(with-input-from-file file
(lambda ()
Line 2,451 ⟶ 2,717:
(string-replace mad-story (car change) (cdr change)))))
 
(play-mad-libs)</langsyntaxhighlight>
 
{{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" perl6line>print S:g[ '<' (.*?) '>' ] = %.{$0} //= prompt "$0? " given slurp;</langsyntaxhighlight>
Sample run:
<pre>$ madlibs walk
Line 2,475 ⟶ 2,741:
 
=={{header|REBOL}}==
<langsyntaxhighlight lang="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>
</lang>
=={{header|Red}}==
While the REBOL GUI version above also works in Red with minor changes, here is a text-only version.
<langsyntaxhighlight Redlang="red">phrase: ask "Enter phrase, leave line empty to terminate:^/"
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</langsyntaxhighlight>
{{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}}==
<langsyntaxhighlight lang="rexx">/*REXX program prompts the user for a template substitutions within a story (MAD LIBS).*/
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. */</langsyntaxhighlight>
Some older REXXes don't have a &nbsp; '''changestr''' &nbsp; BIF, so one is included here &nbsp; ──► &nbsp; [[CHANGESTR.REX]].
<br><br>
Line 2,559 ⟶ 2,825:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="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>
</lang>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">puts "Enter a story, terminated by an empty line:"
story = ""
until (line = gets).chomp.empty?
Line 2,588 ⟶ 2,854:
 
puts
puts story</langsyntaxhighlight>
 
Example
Line 2,603 ⟶ 2,869:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">temp$="<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
k = instr(temp$,"<")
while k
Line 2,615 ⟶ 2,881:
wend
print temp$
wait</langsyntaxhighlight>
{{out}}
<pre>
Line 2,626 ⟶ 2,892:
=={{header|Rust}}==
{{libheader|regex}}
<langsyntaxhighlight lang="rust">extern crate regex;
 
use regex::Regex;
Line 2,668 ⟶ 2,934:
}
println!("Resulting story:\n\n{}", template);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,692 ⟶ 2,958:
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">object MadLibs extends App{
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)
}</langsyntaxhighlight>
{{out}}
<pre><name> went for a walk in the park. <he or she>
Line 2,718 ⟶ 2,984:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 2,748 ⟶ 3,014:
writeln("The story becomes:");
write(story);
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,767 ⟶ 3,033:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">var story = ARGF.slurp;
 
var blanks = Hash.new;
Line 2,779 ⟶ 3,045:
}
 
print story.gsub(/<(.*?)>/, {|s1| blanks{s1} });</langsyntaxhighlight>
 
=={{header|tbas}}==
<langsyntaxhighlight lang="qbasic">SUB BETWEEN$(TXT$, LHS$, RHS$, AFTER)
LET LHS = POS(TXT$, LHS$, AFTER)
IF LHS = 0 THEN
Line 2,830 ⟶ 3,096:
END WHILE
 
PRINT STORY$</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
# Read the template...
Line 2,855 ⟶ 3,121:
puts [string repeat "-" 70]
puts -nonewline [string map $mapping $content]
puts [string repeat "-" 70]</langsyntaxhighlight>
Sample session:
<pre>
Line 2,874 ⟶ 3,140:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">Function mad_libs(s)
<lang vb>
Do
Function mad_libs(s)
If InStr(1,s,"<") <> 0 Then
Do
If start_position = InStr(1,s,"<") <>+ 0 Then1
start_position end_position = InStr(1,s,"<>") + 1
parse_string = Mid(s,start_position,end_position-start_position)
end_position = InStr(1,s,">")
WScript.StdOut.Write parse_string & "? "
parse_string = Mid(s,start_position,end_position-start_position)
input_string = WScript.StdIn.ReadLine
WScript.StdOut.Write parse_string & "? "
s = Replace(s,"<" & parse_string & ">",input_string)
input_string = WScript.StdIn.ReadLine
Else
s = Replace(s,"<" & parse_string & ">",input_string)
Exit Do
Else
End If
Exit Do
Loop
End If
mad_libs = s
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>
</lang>
 
{{Out}}
<pre>F:\>cscript /nologo mad_libs.vbs
<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>
</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.
 
<langsyntaxhighlight lang="vbnet">Imports System.Text
 
Module Program
Line 2,976 ⟶ 3,238:
Console.Write(result)
End Sub
End Module</langsyntaxhighlight>
 
{{out|note=for sample input}}
Line 3,019 ⟶ 3,281:
{{libheader|Wren-pattern}}
{{libheader|Wren-seq}}
<langsyntaxhighlight ecmascriptlang="wren">import "io" for Stdin, Stdout
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)")</langsyntaxhighlight>
 
{{out}}
Line 3,060 ⟶ 3,322:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">story,line,re:=Data(),"",RegExp("(<[^>]+>)");
do{ line=ask("Story: "); story.write(line,"\n") }while(line);
while(re.search(story,True)){
Line 3,068 ⟶ 3,330:
}
println("-----------------");
story.text.print();</langsyntaxhighlight>
{{out}}
<pre>
9,483

edits