P. 1
Haskel Tutorial

Haskel Tutorial

|Views: 132|Likes:
Publicado pordevilvsevil

More info:

Published by: devilvsevil on Oct 23, 2008
Direitos Autorais:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

09/07/2012

pdf

text

original

In a sense, the reason that these items are not functions is that they interact with the
“real world.” Their values depend directly on the real world. Supposing we had a type
RealWorld, we might write these functions as having type:

57

58

CHAPTER 5. BASIC INPUT/OUTPUT

printAString :: RealWorld -> String -> RealWorld
readAString :: RealWorld -> (RealWorld, String)

That is, printAString takes a current state of the world and a string to print;
it then modifies the state of the world in such a way that the string is now printed and
returns this new value. Similarly, readAString takes a current state of the world
and returns a new state of the world, paired with the String that was typed.
This would be a possible way to do IO, though it is more than somewhat unweildy.
In this style (assuming an initial RealWorld state were an argument to main), our
“Name.hs” program from Section 3.8 would look something like:

main rW =

let rW’ = printAString rW "Please enter your name: "
(rW’’,name) = readAString rW’
in printAString rW’’

("Hello, " ++ name ++ ", how are you?")

This is not only hard to read, but prone to error, if you accidentally use the wrong
version of the RealWorld. It also doesn’t model the fact that the program below makes
no sense:

main rW =

let rW’ = printAString rW "Please enter your name: "
(rW’’,name) = readAString rW’
in printAString rW’

-- OOPS!
("Hello, " ++ name ++ ", how are you?")

In this program, the reference to rW’’ on the last line has been changed to a ref-
erence to rW’. It is completely unclear what this program should do. Clearly, it must
read a string in order to have a value for name to be printed. But that means that the
RealWorld has been updated. However, then we try to ignore this update by using an
“old version” of the RealWorld. There is clearly something wrong happening here.
Suffice it to say that doing IO operations in a pure lazy functional language is not

trivial.

You're Reading a Free Preview

Descarregar
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->