[Haskell-beginners] IO question

Ertugrul Soeylemez es at ertes.de
Thu Oct 27 17:04:50 CEST 2011


Rustom Mody <rustompmody at gmail.com> wrote:

> I have this from Peyton Jones awkward squad paper
>
> getTwoChars :: IO (Char,Char)
> getTwoChars = do
>             c1 <- getChar
>             c2 <- getChar
>             return (c1,c2)
>
> Can someone explain what is happening here?
> *Main> getTwoChars
> ab
> ('a','b')

This seems perfectly fine.  The getTwoChars action is one that will
result in a 2-tuple of Chars, when run.  The getChar action is a value
of type IO Char, so it's an action that, when run, yields a Char.  While
defining an IO action like getTwoChars you can use other actions to
build it.  In the context of IO each action is executed in sequence (the
two getChars) you have there, and the "<-" arrow is used to give their
results a name, if you care about them.

The "return x" action is just the action, which will yield x when run,
so "return (c1, c2)" will yield the tuple in conformance to getTwoChar's
type.


> *Main> getTwoChars
> a
> ('\n','a')

This one seems really odd.  Assuming that you typed "a" and then pressed
the Return key, I don't know why it happens for you.  For me it doesn't
happen.  I get the expected ('a', '\n').


Greets,
Ertugrul


-- 
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://ertes.de/





More information about the Beginners mailing list