Mad Libs: Difference between revisions

131 bytes removed ,  7 years ago
→‎{{header|Haskell}}: Fixed wiki formatting glitch (adjusting some names) + hlint, hindent, specified imports
(Added code and example input/output initially omitted)
(→‎{{header|Haskell}}: Fixed wiki formatting glitch (adjusting some names) + hlint, hindent, specified imports)
Line 1,219:
=={{header|Haskell}}==
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)
 
import System.Environment
import qualified DataSystem.Map asEnvironment M(getArgs)
 
import qualified Data.Map as M (Map, lookup, insert, empty)
 
getLines :: IO [String]
getLines = getLines' []reverse <$>>= returngetLines_ . reverse[]
where
getLines'getLines_ xs = do
line <- getLine
case line of
[] -> return xs
_ -> getLines'getLines_ $ line : xs
 
prompt :: String -> IO String
Line 1,236 ⟶ 1,238:
 
getKeyword :: String -> Maybe String
getKeyword ('<':xs) = getKeyword'getKeyword_ xs []
where
getKeyword'getKeyword_ [] _ = Nothing
getKeyword'getKeyword_ (x:'>':_) acc = Just $ '<' : (reverse $ ('>' : x : acc)
getKeyword'getKeyword_ (x:xs) acc = getKeyword'getKeyword_ xs $ x : acc
getKeyword _ = Nothing
 
parseText :: String -> M.Map String String -> IO String
parseText [] _ = return []
parseText line@(l:lx) keywords = do
case getKeyword line of
Nothing -> (l :) -<$> parseText lx keywords >>= return . (l:)
Just keyword -> do
let rest = drop (length keyword) line
case M.lookup keyword keywords of
Nothing -> do
newword <- prompt $ "Enter a word for " ++ keyword ++ ": "
rest' rest_ <- parseText rest $ M.insert keyword newword keywords
return $ newword ++ rest'rest_
Just knownword -> do
rest'rest_ <- parseText rest keywords
return $ knownword ++ rest'rest_
 
main :: IO ()
main = do
args <- getArgs
nlines <- case args of
case args of
[] -> getLines >>= return . unlines
[] -> unlines arg:_ -<$> readFile arggetLines
arg:_ -> readFile arg
nlines'nlines_ <- parseText nlines M.empty
putStrLn ""
putStrLn nlines'nlines_</lang>
 
=={{header|J}}==
9,655

edits