Haskell: use the assign operator (<-) for great victory

I was wondering how to escape Haskell’s “monad jail”. Now I’ve figured it out.

I am writing my little accounting package in Haskell. I have “pure” functions which work on regular lists and suchlike. I have written a little parser that reads the file for data. These pure functions are incompatable with the IO. So I ended up stuffing lots of code into the main function.

But there’s no need to do that. The fix is below.

Suppose I have a “regular” function which does all the complicated, time-consuming process. Let’s call that function ‘process’. For the sake of simplicity, suppose the “complicated” processing looks like this:

import Data.Char

process :: [Char] -> (Int, [Char])
process x =
(length x, map toUpper x)

‘process’ takes a string, and returns a tuple of its length, and upper-case version. It is just for illustrative purposes, you understand.

Now, suppose we want that string to have been read in from stdin. I could define a function:

foo = do
inp <- getLine
print (process inp)

I type ‘foo’, and I am prompted for some input. So I type in some input and press return. The crucial line is: inp <- getLine
which ASSIGNS my input to inp. inp is of type String – plain ol’ regular String. That’s great, because I can now pass that to ‘process’ in the regular way.

Now, what if instead of a simple ‘getLine’, the input is a big expensive operation? Maybe it has to read several big files. If I am working in the Prelude, what I don’t want to do is:

foo = do
input <- bigExpensiveRead
print (process inp)

because if I tweak my process a little and want to experiment, I have to keep doing that bigExpensiveRead. But fear not. What I should do is Prelude> input <- bigExpensiveRead
Now, if I tweak any part of my ‘process’ I can just redo the processing part without having to do the inputting part: Prelude> process input

This will, of course, be completely obvious to seasoned, and even not-so-seasoned, Haskell programmers. But to newbies, it is one of those minor epiphanies. Previously, input and output seemed like an overwhelming obstacle. It’s probably why people new to Haskell are put off, and don’t pursue it any further.

No-one can be told what Haskell is. You have to see it for yourself.


About mcturra2000

Computer programmer living in Scotland.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s