Mad Libs: Difference between revisions

Content added Content deleted
(→‎{{header|Lua}}: added Lua solution)
m (syntax highlighting fixup automation)
Line 32: Line 32:
{{trans|Python}}
{{trans|Python}}


<lang 11l>V template = ‘<name> went for a walk in the park. <he or she>
<syntaxhighlight lang="11l">V template = ‘<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.’


Line 44: Line 44:
print("\nThe story becomes:\n\n"story)
print("\nThe story becomes:\n\n"story)


madlibs(template)</lang>
madlibs(template)</syntaxhighlight>


{{out}}
{{out}}
Line 65: 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.
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.


<lang Ada>with Ada.Text_IO, Ada.Command_Line, String_Helper;
<syntaxhighlight lang="ada">with Ada.Text_IO, Ada.Command_Line, String_Helper;


procedure Madlib is
procedure Madlib is
Line 96: Line 96:
Ada.Text_IO.Put_Line(Text.Element(I));
Ada.Text_IO.Put_Line(Text.Element(I));
end loop;
end loop;
end Madlib;</lang>
end Madlib;</syntaxhighlight>


It uses an auxiliary package String_Helper for simple string functions;
It uses an auxiliary package String_Helper for simple string functions;


<lang Ada>with Ada.Containers.Indefinite_Vectors;
<syntaxhighlight lang="ada">with Ada.Containers.Indefinite_Vectors;


package String_Helper is
package String_Helper is
Line 124: Line 124:
function Get_Vector(Filename: String) return Vector;
function Get_Vector(Filename: String) return Vector;


end String_Helper;</lang>
end String_Helper;</syntaxhighlight>


Here is the implementation of String_Helper:
Here is the implementation of String_Helper:


<lang Ada>with Ada.Strings.Fixed, Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Strings.Fixed, Ada.Text_IO;


package body String_Helper is
package body String_Helper is
Line 178: Line 178:
end Get_Vector;
end Get_Vector;


end String_Helper;</lang>
end String_Helper;</syntaxhighlight>


A sample run (with the story template in t.txt):
A sample run (with the story template in t.txt):
Line 193: Line 193:


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>file f;
<syntaxhighlight lang="aime">file f;
data b;
data b;
list l;
list l;
Line 225: Line 225:
}
}


l.ucall(o_, 0, "\n");</lang>
l.ucall(o_, 0, "\n");</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<lang algol68># Mad Libs style story generation #
<syntaxhighlight lang="algol68"># Mad Libs style story generation #


# gets the story template from the file f. The template terminates with #
# gets the story template from the file f. The template terminates with #
Line 356: Line 356:
story( stand in )
story( stand in )


)</lang>
)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 373: Line 373:


----
----
<syntaxhighlight lang="applescript">
<lang AppleScript>


set theNoun to the text returned of (display dialog "What is your noun?" default answer "")
set theNoun to the text returned of (display dialog "What is your noun?" default answer "")
Line 383: Line 383:
display dialog thePerson & " went for a walk in the park. " & theGender & " found a " & theNoun & ". " & thePerson & " decided to take it home."
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}}==
=={{header|Applesoft BASIC}}==
<lang gwbasic> 100 DIM L$(100),W$(50),T$(50)
<syntaxhighlight lang="gwbasic"> 100 DIM L$(100),W$(50),T$(50)
110 LET M$ = CHR$ (13)
110 LET M$ = CHR$ (13)
120 FOR L = 1 TO 1E9
120 FOR L = 1 TO 1E9
Line 416: Line 416:
380 DATA "<NAME> WENT FOR A WALK IN THE PARK. <HE OR SHE>"
380 DATA "<NAME> WENT FOR A WALK IN THE PARK. <HE OR SHE>"
390 DATA "FOUND A <NOUN>. <NAME> DECIDED TO TAKE IT HOME."
390 DATA "FOUND A <NOUN>. <NAME> DECIDED TO TAKE IT HOME."
990 DATA</lang>
990 DATA</syntaxhighlight>
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>story: strip input "Enter a story: "
<syntaxhighlight lang="rebol">story: strip input "Enter a story: "
vars: unique map match story {/\|([^\|]+)\|/} 'v -> replace v "|" ""
vars: unique map match story {/\|([^\|]+)\|/} 'v -> replace v "|" ""


Line 428: Line 428:
]
]


print ~story</lang>
print ~story</syntaxhighlight>


{{out}}
{{out}}
Line 440: Line 440:
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
Like some other examples, this prompts the user for a text file template.<br/>AutoHotkey is interestingly well suited for this task...
Like some other examples, this prompts the user for a text file template.<br/>AutoHotkey is interestingly well suited for this task...
<lang AHK>FileSelectFile, filename, , %A_ScriptDir%, Select a Mad Libs template, *.txt
<syntaxhighlight lang="ahk">FileSelectFile, filename, , %A_ScriptDir%, Select a Mad Libs template, *.txt
If ErrorLevel
If ErrorLevel
ExitApp ; the user canceled the file selection
ExitApp ; the user canceled the file selection
Line 452: Line 452:
StringReplace, contents, contents, %match%, %repl%, All
StringReplace, contents, contents, %match%, %repl%, All
}
}
MsgBox % contents</lang>
MsgBox % contents</syntaxhighlight>
{{out|Sample Output}}
{{out|Sample Output}}
<pre>Han Solo went for a walk in the park. She
<pre>Han Solo went for a walk in the park. She
Line 458: Line 458:


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f MAD_LIBS.AWK
# syntax: GAWK -f MAD_LIBS.AWK
BEGIN {
BEGIN {
Line 493: Line 493:
exit(0)
exit(0)
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 511: Line 511:


=={{header|BASIC256}}==
=={{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."
cadena = "<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
k = instr(cadena, "<")
k = instr(cadena, "<")
Line 527: Line 527:
print : print "La historia final: " : print cadena
print : print "La historia final: " : print cadena
end
end
</syntaxhighlight>
</lang>




=={{header|C}}==
=={{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.
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 <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
Line 678: Line 678:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 691: Line 691:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <string>
#include <string>
using namespace std;
using namespace std;
Line 738: Line 738:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp}}==
=={{header|C sharp}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Linq;
using System.Text;
using System.Text;
Line 811: Line 811:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(ns magic.rosetta
<syntaxhighlight lang="clojure">(ns magic.rosetta
(:require [clojure.string :as str]))
(:require [clojure.string :as str]))


Line 873: Line 873:
; While Bob Dylan walk, strange man
; While Bob Dylan walk, strange man
; appears and gave Bob Dylan a Nobel prize.
; appears and gave Bob Dylan a Nobel prize.
</syntaxhighlight>
</lang>


=={{header|Commodore BASIC}}==
=={{header|Commodore BASIC}}==
Line 879: Line 879:
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.
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
<syntaxhighlight lang="gwbasic">10 rem mad lib for rosetta code
15 dim bf$(100),wd$(50),tg$(50):tb=49152
15 dim bf$(100),wd$(50),tg$(50):tb=49152
20 print chr$(147);chr$(14);"Mad Lib Processor":print
20 print chr$(147);chr$(14);"Mad Lib Processor":print
Line 964: Line 964:
2105 print:print er;"- ";en$;" at .:";et$;" .:";es$
2105 print:print er;"- ";en$;" at .:";et$;" .:";es$
2110 print:print "Press a key.":gosub 500
2110 print:print "Press a key.":gosub 500
2115 return</lang>
2115 return</syntaxhighlight>


'''Input File'''
'''Input File'''
Line 1,051: Line 1,051:
=={{header|D}}==
=={{header|D}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang d>import std.stdio, std.regex, std.algorithm, std.string, std.array;
<syntaxhighlight lang="d">import std.stdio, std.regex, std.algorithm, std.string, std.array;


void main() {
void main() {
Line 1,070: Line 1,070:


writeln("\nThe story becomes:\n", story);
writeln("\nThe story becomes:\n", story);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Enter a story template, terminated by an empty line:
<pre>Enter a story template, terminated by an empty line:
Line 1,085: Line 1,085:


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>-module(madlib).
<syntaxhighlight lang="erlang">-module(madlib).
-compile(export_all).
-compile(export_all).


Line 1,137: Line 1,137:
lists:foldl(fun ([M],D) ->
lists:foldl(fun ([M],D) ->
dict:store(M,"",D)
dict:store(M,"",D)
end, Dict, Matches).</lang>
end, Dict, Matches).</syntaxhighlight>


This version can be called via either madlib:main() or madlib:main(File) to read from standard_in or from a file.
This version can be called via either madlib:main() or madlib:main(File) to read from standard_in or from a file.
Line 1,144: Line 1,144:


{{out}}
{{out}}
<lang erlang>68> madlib:main("test.mad").
<syntaxhighlight lang="erlang">68> madlib:main("test.mad").
Please name a <noun>: banana
Please name a <noun>: banana
Please name a <name>: Jack
Please name a <name>: Jack
Line 1,150: Line 1,150:
Jack went for a walk in the park. She
Jack went for a walk in the park. She
found a banana. Jack decided to take it home.ok
found a banana. Jack decided to take it home.ok
69> </lang>
69> </syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: formatting io kernel make regexp sequences sets splitting ;
<syntaxhighlight lang="factor">USING: formatting io kernel make regexp sequences sets splitting ;
IN: rosetta-code.mad-libs
IN: rosetta-code.mad-libs


Line 1,174: Line 1,174:
get-mad-lib dup find-replacements replacements nl print ;
get-mad-lib dup find-replacements replacements nl print ;


MAIN: mad-libs</lang>
MAIN: mad-libs</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,227: Line 1,227:
written on it. Joseph the lucky decided to take it home.
written on it. Joseph the lucky decided to take it home.


<syntaxhighlight lang="fortran">
<lang Fortran>
MODULE MADLIB !Messing with COMMON is less convenient.
MODULE MADLIB !Messing with COMMON is less convenient.
INTEGER MSG,KBD,INF !I/O unit numbers.
INTEGER MSG,KBD,INF !I/O unit numbers.
Line 1,467: Line 1,467:
CALL WRITESTORY(66)
CALL WRITESTORY(66)
END
END
</syntaxhighlight>
</lang>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>
<syntaxhighlight lang="freebasic">
Dim As String con, cadena
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."
cadena = "<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
Line 1,488: Line 1,488:
Print Chr(10) & "La historia final: "
Print Chr(10) & "La historia final: "
Print cadena & Chr(10)
Print cadena & Chr(10)
</syntaxhighlight>
</lang>


=={{header|Go}}==
=={{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.)
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.)
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,548: Line 1,548:
return m[p]
return m[p]
}))
}))
}</lang>
}</syntaxhighlight>
Sample run:
Sample run:
<pre>
<pre>
Line 1,564: Line 1,564:
=={{header|Haskell}}==
=={{header|Haskell}}==
This will read a template story via stdin with no arguments, or read from a file if given as an argument.
This will read a template story via stdin with no arguments, or read from a file if given as an argument.
<lang Haskell>import System.IO (stdout, hFlush)
<syntaxhighlight lang="haskell">import System.IO (stdout, hFlush)


import System.Environment (getArgs)
import System.Environment (getArgs)
Line 1,615: Line 1,615:
nlines_ <- parseText nlines M.empty
nlines_ <- parseText nlines M.empty
putStrLn ""
putStrLn ""
putStrLn nlines_</lang>
putStrLn nlines_</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{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.
This just runs with the sample. It would be much more fun with a database of randomly selected story templates.
<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
ml := "<name> went for a walk in the park. There <he or she> _
ml := "<name> went for a walk in the park. There <he or she> _
found a <noun>. <name> decided to take it home." # sample
found a <noun>. <name> decided to take it home." # sample
Line 1,634: Line 1,634:
story := replace(story,v,read())
story := replace(story,v,read())
write("\nYour MadLib follows:\n",story)
write("\nYour MadLib follows:\n",story)
end</lang>
end</syntaxhighlight>


{{libheader|Icon Programming Library}}
{{libheader|Icon Programming Library}}
Line 1,652: Line 1,652:
Implementation:
Implementation:


<lang J>require 'general/misc/prompt regex'
<syntaxhighlight lang="j">require 'general/misc/prompt regex'


madlib=:3 :0
madlib=:3 :0
Line 1,665: Line 1,665:
end.
end.
t
t
)</lang>
)</syntaxhighlight>


Example use:
Example use:


<lang J> madlib''
<syntaxhighlight lang="j"> madlib''
Please enter the story template
Please enter the story template
See http://rosettacode.org/wiki/Mad_Libs for details
See http://rosettacode.org/wiki/Mad_Libs for details
Line 1,680: Line 1,680:
Jill went for a walk in the park. she
Jill went for a walk in the park. she
found a rock. Jill decided to take it home.
found a rock. Jill decided to take it home.
</syntaxhighlight>
</lang>


=={{header|Java}}==
=={{header|Java}}==
I tried to fix this... but this is my first one.
I tried to fix this... but this is my first one.


<lang Java>import java.util.*;
<syntaxhighlight lang="java">import java.util.*;


public class MadLibs {
public class MadLibs {
Line 1,708: Line 1,708:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Julia}}==
=={{header|Julia}}==
Line 1,714: Line 1,714:
{{trans|Python}}
{{trans|Python}}


<lang julia>
<syntaxhighlight lang="julia">
function madlibs(template)
function madlibs(template)
println("The story template is:\n", template)
println("The story template is:\n", template)
Line 1,732: Line 1,732:
"""
"""


madlibs(template)</lang>
madlibs(template)</syntaxhighlight>


{{out}}
{{out}}
Line 1,749: Line 1,749:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 1,770: Line 1,770:
}
}
println("\n$story")
println("\n$story")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,789: Line 1,789:


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>temp$="<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
<syntaxhighlight 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$,"<")
k = instr(temp$,"<")
while k
while k
Line 1,802: Line 1,802:
print temp$
print temp$
wait
wait
</syntaxhighlight>
</lang>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>print("Enter a multi-line story (finish with blank line):")
<syntaxhighlight lang="lua">print("Enter a multi-line story (finish with blank line):")
dict, story, line = {}, "", io.read()
dict, story, line = {}, "", io.read()
while #line>0 do story=story..line.."\n" line=io.read() end
while #line>0 do story=story..line.."\n" line=io.read() end
Line 1,814: Line 1,814:
return dict[what]
return dict[what]
end)
end)
print("\n"..story)</lang>
print("\n"..story)</syntaxhighlight>
{{out}}
{{out}}
<pre>Enter a multi-line story (finish with blank line):
<pre>Enter a multi-line story (finish with blank line):
Line 1,829: Line 1,829:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{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.
Like some other examples, this prompts the user for a filename for a story template rather than reading the story in from user input.
<lang Mathematica>text = Import[
<syntaxhighlight lang="mathematica">text = Import[
InputString["Enter the filename of the story template:"]];
InputString["Enter the filename of the story template:"]];
answers =
answers =
Line 1,839: Line 1,839:
" " <> StringTrim[#, "<" | ">"] <> ":"] &,
" " <> StringTrim[#, "<" | ">"] <> ":"] &,
Union[StringCases[text, RegularExpression["<[^>]+>"]]]];
Union[StringCases[text, RegularExpression["<[^>]+>"]]]];
Print[StringReplace[text, Normal[answers]]];</lang>
Print[StringReplace[text, Normal[answers]]];</syntaxhighlight>
{{out}}
{{out}}
<pre>George went for a walk in the park. he
<pre>George went for a walk in the park. he
Line 1,845: Line 1,845:


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang Nanoquery>def madlib(template)
<syntaxhighlight lang="nanoquery">def madlib(template)
// loop through and find/remove all of the replacements
// loop through and find/remove all of the replacements
replacements = {}
replacements = {}
Line 1,901: Line 1,901:


madlib("<name> went for a walk in the park. <he or she> " + \
madlib("<name> went for a walk in the park. <he or she> " + \
"found a <noun>. <name> decided to take it home.")</lang>
"found a <noun>. <name> decided to take it home.")</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
{{trans|Python}}
{{trans|Python}}
<lang nim>import rdstdin, re, algorithm, sequtils, strutils
<syntaxhighlight lang="nim">import rdstdin, re, algorithm, sequtils, strutils


#let templ = readLineFromStdin "Enter your story: "
#let templ = readLineFromStdin "Enter your story: "
Line 1,920: Line 1,920:
for f,v in zip(fields, values).items:
for f,v in zip(fields, values).items:
story = story.replace(f, v)
story = story.replace(f, v)
echo "\nThe story becomes:\n\n", story</lang>
echo "\nThe story becomes:\n\n", story</syntaxhighlight>
Sample run:
Sample run:
<pre>The story template is:
<pre>The story template is:
Line 1,936: Line 1,936:
=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>: madlibs
<syntaxhighlight lang="oforth">: madlibs
| story i word |
| story i word |
Line 1,946: Line 1,946:
]
]
"Your story :" . story println ;</lang>
"Your story :" . story println ;</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 1,958: Line 1,958:


So, no stories involving < symbols, please.
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}
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,
{Reads the lines of a story but which also contain <xxx> sequences. For each value of xxx,
Line 2,064: Line 2,064:
for i:=1 to StoryLines do Roll(Story[i]); {Write the amended story.}
for i:=1 to StoryLines do Roll(Story[i]); {Write the amended story.}
END.
END.
</syntaxhighlight>
</lang>
Example run:
Example run:
C:\Nicky\Pascal\FILEME~1>MADLIB.EXE
C:\Nicky\Pascal\FILEME~1>MADLIB.EXE
Line 2,075: Line 2,075:
=={{header|Perl}}==
=={{header|Perl}}==
Use the name of the file with a story as the parameter to the programme.
Use the name of the file with a story as the parameter to the programme.
<lang perl>#!/usr/bin/perl
<syntaxhighlight lang="perl">#!/usr/bin/perl
use warnings;
use warnings;
use strict;
use strict;
Line 2,093: Line 2,093:


$story =~ s/<(.*?)>/$blanks{$1}/g;
$story =~ s/<(.*?)>/$blanks{$1}/g;
print $story;</lang>
print $story;</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
Set mlfile to the name of a suitable file, if you have one, otherwise it uses the default story.
Set mlfile to the name of a suitable file, if you have one, otherwise it uses the default story.
<!--<lang Phix>-->
<!--<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: #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: #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>
Line 2,119: Line 2,119:
<span style="color: #008080;">end</span> <span style="color: #008080;">while</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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,129: Line 2,129:
</pre>
</pre>
Removing all file i/o and prompts to make it pwa/p2js compatible, same final output:
Removing all file i/o and prompts to make it pwa/p2js compatible, same final output:
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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;">"""
<span style="color: #004080;">string</span> <span style="color: #000000;">mltxt</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
Line 2,148: Line 2,148:
<span style="color: #008080;">end</span> <span style="color: #008080;">while</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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>"<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
<syntaxhighlight lang="phixmonti">"<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
true
true
while
while
Line 2,169: Line 2,169:
endwhile
endwhile
print
print
</syntaxhighlight>
</lang>


=={{header|Picat}}==
=={{header|Picat}}==
<lang Picat>import util.
<syntaxhighlight lang="picat">import util.


go =>
go =>
Line 2,224: Line 2,224:
once(append(Before,Old,After,Res)),
once(append(Before,Old,After,Res)),
Res := Before ++ New ++ After
Res := Before ++ New ++ After
end.</lang>
end.</syntaxhighlight>


{{out}}
{{out}}
Line 2,247: Line 2,247:
=={{header|PicoLisp}}==
=={{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:
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:
<lang PicoLisp>(de madlib (Template)
<syntaxhighlight lang="picolisp">(de madlib (Template)
(setq Template (split (chop Template) "<" ">"))
(setq Template (split (chop Template) "<" ">"))
(let (Reps () Text ())
(let (Reps () Text ())
Line 2,263: Line 2,263:
(prinl (need 30 '-))
(prinl (need 30 '-))
(prinl (flip Text)) ) )
(prinl (flip Text)) ) )
</syntaxhighlight>
</lang>


This runs the example:
This runs the example:
Line 2,303: Line 2,303:
=={{header|Pike}}==
=={{header|Pike}}==
this solution uses readline to make editing more convenient.
this solution uses readline to make editing more convenient.
<lang Pike>#!/usr/bin/pike
<syntaxhighlight lang="pike">#!/usr/bin/pike
Stdio.Readline readln = Stdio.Readline();
Stdio.Readline readln = Stdio.Readline();
Line 2,386: Line 2,386:
else add_line(input);
else add_line(input);
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,423: Line 2,423:
=={{header|PL/I}}==
=={{header|PL/I}}==
{{incorrect|PL/I|This seems to hard code the replaceable symbols instead of taking them from the story.}}
{{incorrect|PL/I|This seems to hard code the replaceable symbols instead of taking them from the story.}}
<lang PL/I>(stringrange, stringsize): /* 2 Nov. 2013 */
<syntaxhighlight lang="pl/i">(stringrange, stringsize): /* 2 Nov. 2013 */
Mad_Libs: procedure options (main);
Mad_Libs: procedure options (main);
declare (line, left, right) character (100) varying;
declare (line, left, right) character (100) varying;
Line 2,493: Line 2,493:
end split;
end split;


end Mad_Libs;</lang>
end Mad_Libs;</syntaxhighlight>
<pre>
<pre>
Please type a name:
Please type a name:
Line 2,504: Line 2,504:


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function New-MadLibs
function New-MadLibs
{
{
Line 2,570: Line 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
"`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:
Command line input:
<syntaxhighlight lang="powershell">
<lang PowerShell>
New-MadLibs -Name hank -Male -Item shank
New-MadLibs -Name hank -Male -Item shank
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,580: Line 2,580:
</pre>
</pre>
Prompt for input:
Prompt for input:
<syntaxhighlight lang="powershell">
<lang PowerShell>
New-MadLibs
New-MadLibs
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,599: Line 2,599:
</pre>
</pre>
Command line input using splatting:
Command line input using splatting:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$paramLists = @(@{Name='mary'; Female=$true; Item="little lamb"},
$paramLists = @(@{Name='mary'; Female=$true; Item="little lamb"},
@{Name='hank'; Male=$true; Item="shank"},
@{Name='hank'; Male=$true; Item="shank"},
Line 2,608: Line 2,608:
New-MadLibs @paramList
New-MadLibs @paramList
}
}
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,623: Line 2,623:
=={{header|PureBasic}}==
=={{header|PureBasic}}==
{{trans|FreeBASIC}}
{{trans|FreeBASIC}}
<syntaxhighlight lang="purebasic">
<lang PureBasic>
If OpenConsole()
If OpenConsole()
Line 2,647: Line 2,647:
EndIf
EndIf
End
End
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,654: Line 2,654:


=={{header|Python}}==
=={{header|Python}}==
<lang python>import re
<syntaxhighlight lang="python">import re


# Optional Python 2.x compatibility
# Optional Python 2.x compatibility
Line 2,673: Line 2,673:
print('\nThe story becomes:\n\n' + story)
print('\nThe story becomes:\n\n' + story)


madlibs(template)</lang>
madlibs(template)</syntaxhighlight>


{{out}}
{{out}}
Line 2,690: Line 2,690:
=={{header|Racket}}==
=={{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
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
<lang Racket>(define (get-mad-libs file)
<syntaxhighlight lang="racket">(define (get-mad-libs file)
(with-input-from-file file
(with-input-from-file file
(lambda ()
(lambda ()
Line 2,717: Line 2,717:
(string-replace mad-story (car change) (cdr change)))))
(string-replace mad-story (car change) (cdr change)))))


(play-mad-libs)</lang>
(play-mad-libs)</syntaxhighlight>


{{out}} with the story from this page
{{out}} with the story from this page
Line 2,731: Line 2,731:
{{works with|rakudo|2015-09-18}}
{{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.
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.
<lang perl6>print S:g[ '<' (.*?) '>' ] = %.{$0} //= prompt "$0? " given slurp;</lang>
<syntaxhighlight lang="raku" line>print S:g[ '<' (.*?) '>' ] = %.{$0} //= prompt "$0? " given slurp;</syntaxhighlight>
Sample run:
Sample run:
<pre>$ madlibs walk
<pre>$ madlibs walk
Line 2,741: Line 2,741:


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang rebol>
<syntaxhighlight lang="rebol">
t: {<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home.}
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]]
view layout [a: area wrap t btn "Done" [x: a/text unview]]
parse x [any [to "<" copy b thru ">" (append w: [] b)] to end]
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
foreach i unique w [replace/all x i ask join i ": "] alert x
</syntaxhighlight>
</lang>
=={{header|Red}}==
=={{header|Red}}==
While the REBOL GUI version above also works in Red with minor changes, here is a text-only version.
While the REBOL GUI version above also works in Red with minor changes, here is a text-only version.
<lang Red>phrase: ask "Enter phrase, leave line empty to terminate:^/"
<syntaxhighlight lang="red">phrase: ask "Enter phrase, leave line empty to terminate:^/"
while [not empty? line: input] [append phrase rejoin ["^/" line]]
while [not empty? line: input] [append phrase rejoin ["^/" line]]
words: parse phrase [collect [any [to "<" copy b thru ">" keep (b)]]]
words: parse phrase [collect [any [to "<" copy b thru ">" keep (b)]]]
foreach w unique words [replace/all phrase w ask rejoin [w ": "]]
foreach w unique words [replace/all phrase w ask rejoin [w ": "]]
print phrase</lang>
print phrase</syntaxhighlight>
{{out}}
{{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:
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,771: Line 2,771:


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX program prompts the user for a template substitutions within a story (MAD LIBS).*/
<syntaxhighlight 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.*/
parse arg iFID . /*allow user to specify the input file.*/
if iFID=='' | iFID=="," then iFID="MAD_LIBS.TXT" /*Not specified? Then use the default.*/
if iFID=='' | iFID=="," then iFID="MAD_LIBS.TXT" /*Not specified? Then use the default.*/
Line 2,805: Line 2,805:


say copies('═', 79) /*display a final (output) fence. */
say copies('═', 79) /*display a final (output) fence. */
say /*stick a fork in it, we're all done. */</lang>
say /*stick a fork in it, we're all done. */</syntaxhighlight>
Some older REXXes don't have a &nbsp; '''changestr''' &nbsp; BIF, so one is included here &nbsp; ──► &nbsp; [[CHANGESTR.REX]].
Some older REXXes don't have a &nbsp; '''changestr''' &nbsp; BIF, so one is included here &nbsp; ──► &nbsp; [[CHANGESTR.REX]].
<br><br>
<br><br>
Line 2,825: Line 2,825:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
temp="<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
temp="<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
k = substr(temp,"<")
k = substr(temp,"<")
Line 2,839: Line 2,839:
end
end
see temp + nl
see temp + nl
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>puts "Enter a story, terminated by an empty line:"
<syntaxhighlight lang="ruby">puts "Enter a story, terminated by an empty line:"
story = ""
story = ""
until (line = gets).chomp.empty?
until (line = gets).chomp.empty?
Line 2,854: Line 2,854:


puts
puts
puts story</lang>
puts story</syntaxhighlight>


Example
Example
Line 2,869: Line 2,869:


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>temp$="<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
<syntaxhighlight 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$,"<")
k = instr(temp$,"<")
while k
while k
Line 2,881: Line 2,881:
wend
wend
print temp$
print temp$
wait</lang>
wait</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,892: Line 2,892:
=={{header|Rust}}==
=={{header|Rust}}==
{{libheader|regex}}
{{libheader|regex}}
<lang rust>extern crate regex;
<syntaxhighlight lang="rust">extern crate regex;


use regex::Regex;
use regex::Regex;
Line 2,934: Line 2,934:
}
}
println!("Resulting story:\n\n{}", template);
println!("Resulting story:\n\n{}", template);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,958: Line 2,958:


=={{header|Scala}}==
=={{header|Scala}}==
<lang Scala>object MadLibs extends App{
<syntaxhighlight lang="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."
val input = "<name> went for a walk in the park. <he or she>\nfound a <noun>. <name> decided to take it home."
println(input)
println(input)
Line 2,971: Line 2,971:
println
println
println(output)
println(output)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre><name> went for a walk in the park. <he or she>
<pre><name> went for a walk in the park. <he or she>
Line 2,984: Line 2,984:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const proc: main is func
const proc: main is func
Line 3,014: Line 3,014:
writeln("The story becomes:");
writeln("The story becomes:");
write(story);
write(story);
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 3,033: Line 3,033:
=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Perl}}
{{trans|Perl}}
<lang ruby>var story = ARGF.slurp;
<syntaxhighlight lang="ruby">var story = ARGF.slurp;


var blanks = Hash.new;
var blanks = Hash.new;
Line 3,045: Line 3,045:
}
}


print story.gsub(/<(.*?)>/, {|s1| blanks{s1} });</lang>
print story.gsub(/<(.*?)>/, {|s1| blanks{s1} });</syntaxhighlight>


=={{header|tbas}}==
=={{header|tbas}}==
<lang qbasic>SUB BETWEEN$(TXT$, LHS$, RHS$, AFTER)
<syntaxhighlight lang="qbasic">SUB BETWEEN$(TXT$, LHS$, RHS$, AFTER)
LET LHS = POS(TXT$, LHS$, AFTER)
LET LHS = POS(TXT$, LHS$, AFTER)
IF LHS = 0 THEN
IF LHS = 0 THEN
Line 3,096: Line 3,096:
END WHILE
END WHILE


PRINT STORY$</lang>
PRINT STORY$</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>package require Tcl 8.5
<syntaxhighlight lang="tcl">package require Tcl 8.5


# Read the template...
# Read the template...
Line 3,121: Line 3,121:
puts [string repeat "-" 70]
puts [string repeat "-" 70]
puts -nonewline [string map $mapping $content]
puts -nonewline [string map $mapping $content]
puts [string repeat "-" 70]</lang>
puts [string repeat "-" 70]</syntaxhighlight>
Sample session:
Sample session:
<pre>
<pre>
Line 3,140: Line 3,140:


=={{header|VBScript}}==
=={{header|VBScript}}==
<lang vb>Function mad_libs(s)
<syntaxhighlight lang="vb">Function mad_libs(s)
Do
Do
If InStr(1,s,"<") <> 0 Then
If InStr(1,s,"<") <> 0 Then
Line 3,157: Line 3,157:


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.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</lang>
WScript.StdOut.WriteLine</syntaxhighlight>


{{Out}}
{{Out}}
Line 3,170: Line 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.
"\<" 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.


<lang vbnet>Imports System.Text
<syntaxhighlight lang="vbnet">Imports System.Text


Module Program
Module Program
Line 3,238: Line 3,238:
Console.Write(result)
Console.Write(result)
End Sub
End Sub
End Module</lang>
End Module</syntaxhighlight>


{{out|note=for sample input}}
{{out|note=for sample input}}
Line 3,281: Line 3,281:
{{libheader|Wren-pattern}}
{{libheader|Wren-pattern}}
{{libheader|Wren-seq}}
{{libheader|Wren-seq}}
<lang ecmascript>import "io" for Stdin, Stdout
<syntaxhighlight lang="ecmascript">import "io" for Stdin, Stdout
import "/pattern" for Pattern
import "/pattern" for Pattern
import "/seq" for Lst
import "/seq" for Lst
Line 3,303: Line 3,303:
story = story.replace(blank, repl)
story = story.replace(blank, repl)
}
}
System.print("\n%(story)")</lang>
System.print("\n%(story)")</syntaxhighlight>


{{out}}
{{out}}
Line 3,322: Line 3,322:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>story,line,re:=Data(),"",RegExp("(<[^>]+>)");
<syntaxhighlight lang="zkl">story,line,re:=Data(),"",RegExp("(<[^>]+>)");
do{ line=ask("Story: "); story.write(line,"\n") }while(line);
do{ line=ask("Story: "); story.write(line,"\n") }while(line);
while(re.search(story,True)){
while(re.search(story,True)){
Line 3,330: Line 3,330:
}
}
println("-----------------");
println("-----------------");
story.text.print();</lang>
story.text.print();</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>