10 - Imperative functional programming
Published online by Cambridge University Press: 05 November 2014
Summary
Back in Chapter 2 we described the function putStrLn as being a Haskell command, and IO a as being the type of input–output computations that interact with the outside world and deliver values of type a. We also mentioned some syntax, called do-notation, for sequencing commands. This chapter explores what is really meant by these words, and introduces a new style of programming called monadic programming. Monadic programs provide a simple and attractive way to describe interaction with the outside world, but are also capable of much more: they provide a simple sequencing mechanism for solving a range of problems, including exception handling, destructive array updates, parsing and state-based computation. In a very real sense, a monadic style enables us to write functional programs that mimic the kind of imperative programs one finds in languages such as Python or C.
The IO monad
The type IO a is an abstract type in the sense described in the previous chapter, so we are not told how its values, which are called actions or commands, are represented. But you can think of this type as being
type IO a = World → (a, World)
Thus an action is a function that takes a world and delivers a value of type a and a new world.
- Type
- Chapter
- Information
- Thinking Functionally with Haskell , pp. 239 - 275Publisher: Cambridge University PressPrint publication year: 2014