Mad Libs: Difference between revisions
m
syntax highlighting fixup automation
(→{{header|Lua}}: added Lua solution) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
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}}==
<
110 LET M$ = CHR$ (13)
120 FOR L = 1 TO 1E9
Line 416:
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</
=={{header|Arturo}}==
<
vars: unique map match story {/\|([^\|]+)\|/} 'v -> replace v "|" ""
Line 428:
]
print ~story</
{{out}}
Line 440:
=={{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 452:
StringReplace, contents, contents, %match%, %repl%, All
}
MsgBox % contents</
{{out|Sample Output}}
<pre>Han Solo went for a walk in the park. She
Line 458:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f MAD_LIBS.AWK
BEGIN {
Line 493:
exit(0)
}
</syntaxhighlight>
{{out}}
<pre>
Line 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 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 678:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
Line 691:
=={{header|C++}}==
<
#include <string>
using namespace std;
Line 738:
return 0;
}</
=={{header|C sharp}}==
<
using System.Linq;
using System.Text;
Line 811:
}
}
</syntaxhighlight>
=={{header|Clojure}}==
<
(:require [clojure.string :as str]))
Line 873:
; While Bob Dylan walk, strange man
; appears and gave Bob Dylan a Nobel prize.
</syntaxhighlight>
=={{header|Commodore BASIC}}==
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.
<
15 dim bf$(100),wd$(50),tg$(50):tb=49152
20 print chr$(147);chr$(14);"Mad Lib Processor":print
Line 964:
2105 print:print er;"- ";en$;" at .:";et$;" .:";es$
2110 print:print "Press a key.":gosub 500
2115 return</
'''Input File'''
Line 1,051:
=={{header|D}}==
{{trans|Ruby}}
<
void main() {
Line 1,070:
writeln("\nThe story becomes:\n", story);
}</
{{out}}
<pre>Enter a story template, terminated by an empty line:
Line 1,085:
=={{header|Erlang}}==
<
-compile(export_all).
Line 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,144:
{{out}}
<
Please name a <noun>: banana
Please name a <name>: Jack
Line 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,174:
get-mad-lib dup find-replacements replacements nl print ;
MAIN: mad-libs</
{{out}}
<pre>
Line 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,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,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,548:
return m[p]
}))
}</
Sample run:
<pre>
Line 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,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,634:
story := replace(story,v,read())
write("\nYour MadLib follows:\n",story)
end</
{{libheader|Icon Programming Library}}
Line 1,652:
Implementation:
<
madlib=:3 :0
Line 1,665:
end.
t
)</
Example use:
<
Please enter the story template
See http://rosettacode.org/wiki/Mad_Libs for details
Line 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,708:
}
}
</syntaxhighlight>
=={{header|Julia}}==
Line 1,714:
{{trans|Python}}
<
function madlibs(template)
println("The story template is:\n", template)
Line 1,732:
"""
madlibs(template)</
{{out}}
Line 1,749:
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 1,770:
}
println("\n$story")
}</
{{out}}
Line 1,789:
=={{header|Liberty BASIC}}==
<
k = instr(temp$,"<")
while k
Line 1,802:
print temp$
wait
</syntaxhighlight>
=={{header|Lua}}==
<
dict, story, line = {}, "", io.read()
while #line>0 do story=story..line.."\n" line=io.read() end
Line 1,814:
return dict[what]
end)
print("\n"..story)</
{{out}}
<pre>Enter a multi-line story (finish with blank line):
Line 1,829:
=={{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,839:
" " <> StringTrim[#, "<" | ">"] <> ":"] &,
Union[StringCases[text, RegularExpression["<[^>]+>"]]]];
Print[StringReplace[text, Normal[answers]]];</
{{out}}
<pre>George went for a walk in the park. he
Line 1,845:
=={{header|Nanoquery}}==
<
// loop through and find/remove all of the replacements
replacements = {}
Line 1,901:
madlib("<name> went for a walk in the park. <he or she> " + \
"found a <noun>. <name> decided to take it home.")</
=={{header|Nim}}==
{{trans|Python}}
<
#let templ = readLineFromStdin "Enter your story: "
Line 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,936:
=={{header|Oforth}}==
<
| story i word |
Line 1,946:
]
"Your story :" . story println ;</
=={{header|Pascal}}==
Line 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 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 2,075:
=={{header|Perl}}==
Use the name of the file with a story as the parameter to the programme.
<
use warnings;
use strict;
Line 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.
<!--<
<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>
Line 2,119:
<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>
<!--</
{{out}}
<pre>
Line 2,129:
</pre>
Removing all file i/o and prompts to make it pwa/p2js compatible, same final output:
<!--<
<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;">"""
Line 2,148:
<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>
<!--</
=={{header|Phixmonti}}==
<
true
while
Line 2,169:
endwhile
print
</syntaxhighlight>
=={{header|Picat}}==
<
go =>
Line 2,224:
once(append(Before,Old,After,Res)),
Res := Before ++ New ++ After
end.</
{{out}}
Line 2,247:
=={{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,263:
(prinl (need 30 '-))
(prinl (flip Text)) ) )
</syntaxhighlight>
This runs the example:
Line 2,303:
=={{header|Pike}}==
this solution uses readline to make editing more convenient.
<
Stdio.Readline readln = Stdio.Readline();
Line 2,386:
else add_line(input);
}
}</
{{out}}
Line 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,493:
end split;
end Mad_Libs;</
<pre>
Please type a name:
Line 2,504:
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function New-MadLibs
{
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
}
</syntaxhighlight>
Command line input:
<syntaxhighlight lang="powershell">
New-MadLibs -Name hank -Male -Item shank
</syntaxhighlight>
{{Out}}
<pre>
Line 2,580:
</pre>
Prompt for input:
<syntaxhighlight lang="powershell">
New-MadLibs
</syntaxhighlight>
{{Out}}
<pre>
Line 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,608:
New-MadLibs @paramList
}
</syntaxhighlight>
{{Out}}
<pre>
Line 2,623:
=={{header|PureBasic}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="purebasic">
If OpenConsole()
Line 2,647:
EndIf
End
</syntaxhighlight>
{{out}}
<pre>
Line 2,654:
=={{header|Python}}==
<
# Optional Python 2.x compatibility
Line 2,673:
print('\nThe story becomes:\n\n' + story)
madlibs(template)</
{{out}}
Line 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,717:
(string-replace mad-story (car change) (cdr change)))))
(play-mad-libs)</
{{out}} with the story from this page
Line 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,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,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,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,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,839:
end
see temp + nl
</syntaxhighlight>
=={{header|Ruby}}==
<
story = ""
until (line = gets).chomp.empty?
Line 2,854:
puts
puts story</
Example
Line 2,869:
=={{header|Run BASIC}}==
<
k = instr(temp$,"<")
while k
Line 2,881:
wend
print temp$
wait</
{{out}}
<pre>
Line 2,892:
=={{header|Rust}}==
{{libheader|regex}}
<
use regex::Regex;
Line 2,934:
}
println!("Resulting story:\n\n{}", template);
}</
{{out}}
<pre>
Line 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,971:
println
println(output)
}</
{{out}}
<pre><name> went for a walk in the park. <he or she>
Line 2,984:
=={{header|Seed7}}==
<
const proc: main is func
Line 3,014:
writeln("The story becomes:");
write(story);
end func;</
{{out}}
Line 3,033:
=={{header|Sidef}}==
{{trans|Perl}}
<
var blanks = Hash.new;
Line 3,045:
}
print story.gsub(/<(.*?)>/, {|s1| blanks{s1} });</
=={{header|tbas}}==
<
LET LHS = POS(TXT$, LHS$, AFTER)
IF LHS = 0 THEN
Line 3,096:
END WHILE
PRINT STORY$</
=={{header|Tcl}}==
<
# Read the template...
Line 3,121:
puts [string repeat "-" 70]
puts -nonewline [string map $mapping $content]
puts [string repeat "-" 70]</
Sample session:
<pre>
Line 3,140:
=={{header|VBScript}}==
<
Do
If InStr(1,s,"<") <> 0 Then
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.WriteLine</
{{Out}}
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.
<
Module Program
Line 3,238:
Console.Write(result)
End Sub
End Module</
{{out|note=for sample input}}
Line 3,281:
{{libheader|Wren-pattern}}
{{libheader|Wren-seq}}
<
import "/pattern" for Pattern
import "/seq" for Lst
Line 3,303:
story = story.replace(blank, repl)
}
System.print("\n%(story)")</
{{out}}
Line 3,322:
=={{header|zkl}}==
<
do{ line=ask("Story: "); story.write(line,"\n") }while(line);
while(re.search(story,True)){
Line 3,330:
}
println("-----------------");
story.text.print();</
{{out}}
<pre>
|