[Haskell-cafe] Haskell IO problem
Tillmann Rendel
rendel at cs.au.dk
Sun May 10 11:23:00 EDT 2009
Hi apple,
applebiz89 wrote:
> // Say I have this as my data type and list of films
> data Film = Film String String Int [String]
> -- List of films
>
> testDatabase :: [Film]
> testDatabase = [(Film "Casino Royale" "Martin Campbell" 2006 ["Garry",
> "Dave", "Zoe"]) ]
>
> // with functions such as:
>
> becomeFan :: String -> String -> [Film] -> [Film]
> filmsInGivenYear :: Int -> [Film] -> [String]
>
> // I want to ask the user what function they want to use
Once again, it is important to write small blocks of code first. Let's
write an IO wrapper around one of the functions, e.g. around
filmsInGivenYear:
-- Given a films database, this operation asks the user for a year,
-- and then prints the names of all the films from that year.
doFilmsInGivenYear :: [Film] -> IO ()
doFilmsInGivenYear films = do
-- an action
putStrLn "which year?"
-- an action which returns a result
text <- getLine
-- some pure computations
let year = read text :: Int
let answer = filmsInGivenYear year films
-- an action
print answer
For now, we want main to be just doFilmsInGivenYear using the testDatabase:
main :: IO ()
main = doFilmsInGivenYear films
If you compile and run that program, it should ask you for a year, and
then print the films of that year. Then it exists, because there are no
more actions to do.
If you want the program to go on asking you stuff, you can call main again:
main :: IO ()
main = do
doFilmsInGivenYear films
main
If you compile this program and run it, it will run forever and keep
asking you about years. (Strg-C should stop it again).
*After you have tried that out*, you could try to add code to main to
ask the user whether she wants to stop.
Tillmann
PS. Please don't send questions only to me, I am not your private tutor
:) Send to the list instead.
PPS. It is really important to compile your program often, and/or test
it with ghci. It is much easier to do one small step after another
More information about the Haskell-Cafe
mailing list