[Published in Open Source For You (OSFY) magazine, December 2014 edition.]

This article is a must read for anyone interested in getting a good insight into the input/output (IO) functionality of Haskell.

Input/output (IO) can cause side-effects and hence is implemented as a Monad. The IO Monad takes some input, does some computation and returns a value. The IO action is performed inside a main function. Consider a simple ‘Hello world’ example:

ghci> main
Enter text:
a
a
it
it
the
the
four
four
empty
twelve
haskell
o
o

You can break out of this execution by pressing Ctrl-c at the GHCi prompt.

The openFile, hGetContents, hClose functions can be used to obtain a handle for a file, to retrieve the file contents, and to close the handle respectively. This is similar to file handling in C. Their type signatures are shown below:

You must ensure to remove the file after using it. An example is given below:

ghci> main
/tmp/abc2731

The operations on opening a file to get a handle, getting the contents, and closing the handle can be abstracted to a higher level. The readFile and writeFile functions can be used for this purpose. Their type signatures are as follows:

The System.Environment module has useful functions to read command line arguments. The getArgs function returns an array of arguments passed to the program. The getProgName provides the name of the program being executed. Their type signatures are shown below:

To know the current directory from where you are running the command, you can use the getCurrentDirectory function, and to know the contents in a directory you can use the getDirectoryContents function. Their type signatures are: