Simple I/O in Haskell
/*********************************************** * Image Thumbnail Viewer Script- © Dynamic Drive (www.dynamicdrive.com) * This notice must stay intact for legal use. * Visit http://www.dynamicdrive.com/ for full source code ***********************************************/
I am writing this based on the fact that you have read Hello World series; if not, refer to my Haskell Basics Page.
From this point on, i will generally follow these steps :
- Step 1: Write the module / code in Eclipse editor.
- Step 2 : Compile it using CTRL + F11
- Run it on command prompt (refer to Haskell Basics Page for pattern of usage) to display what we did.
So here we go; lets do something very basic, the first thing i would want is to get input from a user and display some data, make my program interactive.
module Main where
main = do putStrLn “What is 2 + 2?”
x <- readLn
if x == 4
then putStrLn "You're right!"
else putStrLn "You're wrong dude, go to elementary school!"
Pay Strict attention to indentation in this code, it can cause errors from haskell parser. More on that later (i had a lot of trouble with this as i am not familiar with Python personally).
So what do we have here ? well first you declare a main type with a ‘do’. You basically use a ‘do’ when you want to do multiple actions at once. The thing to note here is line 2.
x<- readLn, this takes in the input and then infers to bring the result. Off course our inference is naive looking but it serves the purpose.
Here’s the O/P:
Click to see the output!
If you still have problems (despite copying the above code, get back to me, i’ll copy the actual files may be (tell me if there’s a better way of doing this).
Next we”ll explore Types in haskell.
Regards
Vyas, Anirudh