Skip to main content
edited tags; edited title
Link
200_success
  • 145.7k
  • 22
  • 191
  • 481

Recursive Mad Libs using recursive IO for user input

Source Link
Pappa
  • 133
  • 4

Recursive IO for user input

I'm writing my first small programs in Haskell and still getting a feel for the syntax and idioms. I've written this Mad Libs implementation using recursive IO. I've used IO actions throughout and I'm sure there must be a better way of splitting up this code to separate pure functions from IO actions. Also, I'm not happy with the printf statement, but I couldn't find a native way to apply an arbitrary number of list items to printf.

import Text.Printf

getAnswer :: String -> IO String
getAnswer question = do
    putStrLn question
    answer <- getLine
    return answer

getAnswers :: [String] -> [String] -> IO [String]
getAnswers [] ys = return ys
getAnswers (x:xs) ys = do
    answer <- getAnswer x
    let answers = ys ++ [answer]
    getAnswers xs answers

main = do
    let questions = ["Enter a noun:", "Enter a verb:", "Enter an adjective:", "Enter an adverb:"]
    let madlib = "Your %s is %s up a %s mountain %s."
    answers <- getAnswers questions []
    printf madlib (answers!!0) (answers!!1) (answers!!2) (answers!!3)
    putStrLn ""