As we mentioned earlier, it is difficult to think of a good, clean way to integrate operations like input/output into a pure functional language., there should be no problem with replacing it with a function
f _ = (), due to referential transparency. But clearly this does not have the desired effect.
The RealWorld SolutionEdit unwieldy. In this style (assuming an initial
RealWorld state were an argument to
main), our "Name.hs" program from the section on Interactivity.
Suffice it to say that doing IO operations in a pure lazy functional language is not trivial.
ActionsEdit defined within Haskell with no special handling from the compiler (though compilers often choose to optimize monadic operations).
As pointed out before, we cannot think of things like "print a string to the screen" or "read data from a file" `run' the chapter Monads). instance, the value of type
IO); } }
Here, because we have the
return () in the first
if match, we expect the code to exit there (and in most num else do print "Too high!"; doGuessing num
will not behave as you expect. First of all, if you guess correctly, it will first.
The IO LibraryEdit
The IO Library (available by importing the
IO module) contains many definitions, the most common of which are listed below: () bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
Note
The type
FilePath is a type synonym for
String. That is, there is no difference between
FilePath and
String. So, for instance, the
readFile function takes a
String (the file to read) and returns an action that, when run, produces the contents of that file. See the section on Synonyms for more about type synonyms.
Most of these functions are self-explanatory. The
openFile and
hClose functions open and close a file, respectively, using the
IOMode argument as an entire file without having to open it first.
The
bracket function is used to perform actions safely. (try reading a non-existent file). file specified. file that doesn't already exists or if you specify some bad filename like
*\^\#_@. the section on Exceptions.