Download Introduction to Haskell Programming Language and more Lecture notes Programming Languages in PDF only on Docsity!
CSEP505: Programming Languages
Lecture 8: Haskell, Laziness, IO Monad
Dan Grossman Autumn 2016
Acknowledgments
- Slide-and-code content liberally appropriated with permission from Kathleen Fisher, Tufts University
- She in turn acknowledges Simon Peyton Jones, Microsoft Research, Cambridge âfor many of these slidesâ
- And then I probably introduced errors and weaknesses as I changed themâŚ
Lecture 8 CSE P505 Autumn 2016 Dan Grossman 2
References
- âReal World Haskellâ,
- Particularly Chapters 0 & 7
- http://book.realworldhaskell.org/
- âTackling the Awkward Squadâ
- Particularly Sections 1 & 2
- http://research.microsoft.com/~simonpj/papers/marktoberdor f/mark.pdf
Lecture 8 CSE P505 Autumn 2016 Dan Grossman 3
Haskell
- Haskell is a programming language that is:
- Similar to ML: general-purpose, strongly typed, higher-order, functional, supports type inference, âŚ
- Different from ML: purely functional core, lazy evaluation, monadic IO, type classes, âŚ
- These differences are why we will use it for Homework 5 and what we will focus on
- Designed by committee in 1980s and 1990s to unify research efforts in lazy languages. Continues to evolve. - Haskell 1.0 in 1990, Haskell â98, Haskellâ ongoing. - âA History of Haskell: Being Lazy with Classâ HOPL 3
Lecture 8 CSE P505 Autumn 2016 Dan Grossman 4
These âgraphsâ arenât mine and arenât based on real data, but theyâre fun [and make a meta-point ?]
Lecture 8 CSE P505 Autumn 2016 Dan Grossman 5
Successful Research Languages
1yr 5yr 10yr 15yr
The slow death
Geeks
Practitioners
Committee languages
1yr 5yr 10yr 15yr
The even slower death
Geeks
Practitioners
C++, Java, Perl, Ruby
1yr 5yr 10yr 15yr
The complete
absence of death
Geeks
Practitioners
Threshold of immortality
Haskell
The second life?
Geeks
Practitioners
Function types mean more
Thanks to purity , a function type is a stronger spec in Haskell:
- If f :: A -> B, then for every e :: A, we know f e
- Equals some v :: B, or
- Does not terminate [hand-wave exceptions, âŚ]
- If e1 = e2, then f e1 = f e
- A âbigger deal than it looksâ â âno side effects or implicit stateâ
- let x = f e in (x,x) is indistinguishable from (f e, f e)
Lecture 8 CSE P505 Autumn 2016 Dan Grossman 10
Ah, xkcd
http://xkcd.com/1312/
Syntax differences from OCaml
- x :: Int means âx has type Intâ
- y : ys means âcons y onto list ysâ
- \x -> x + 1 â\â means lambda
- Required upper/lowercase:
- Expression identifiers are lowercase
- Type constructors (names) are uppercase
- Type variables are lower case (and no â)
- Comments:
- -- to end of line
- {- ⌠-}
- At top-level no âletâ for bindings
- In other scopes, let or where with latter common
- Whitespace relevant (no | on case branches, âŚ)
Back to purity
- Pure functions are easy to test â âno side effectsâ
- Example: If xs = reverse(reverse xs), then you can replace one with the other with high confidence
- And testing this property cannot depend on any state because if reverse is pure (and everything in âcore Haskellâ is pure), then it cannot depend on that state
Lecture 8 CSE P505 Autumn 2016 Dan Grossman 19
Purity is beautiful
- Like in OCaml: higher-order functions, algebraic data types, parametric polymorphism, ...
- Plus equational reasoning due to âno side effectsâ and âonly needed computations evaluatedâ - If x = y, then f x = f y - Order of evaluation is irrelevant, so donât have to âthink about it being lazyâ except for termination/performance
Lecture 8 CSE P505 Autumn 2016 Dan Grossman 20
⌠and the beast
- But to be useful as well as beautiful , a language must manage the âAwkward Squadâ: - Input/Output - Imperative update - Error recovery (e.g., timing out, catching divide by zero, etc.) - Foreign-language interfaces - Concurrency
The whole point of a running a program is to affect the real world, an âupdate in placeâ of something
Lecture 8 CSE P505 Autumn 2016 Dan Grossman 21
Direct approach
- Could allow side effects âthe usual wayâ and discourage them
- Example: putchar :: Char -> ()
- And similar for references, exceptions, ffi, concurrency
- In practice, this works fine in an eager language (cf. OCaml) but is unworkable in a lazy language - Makes evaluation order relevant again - And laziness is hard to reason about - And compiler wants freedom to optimize away laziness when it can tell âit wonât matterâ
- This also doesnât work at the semantics level if we define our language to have âundefined evaluation orderâ rather than lazy - As Haskell does⌠Lecture 8 CSE P505 Autumn 2016 Dan Grossman 22
Examples
Evaluation order of function arguments and data constructor arguments does not matter (and isnât defined) when functions are pure.
Example: ((\x y. y) (putchar âwâ) [putchar âxâ, putchar âyâ]
With lazy implementation output still depends on how result is used
By the way:
- What about exceptions?
- Non-deterministic evaluation order âso any exception might happenâ works okay in practice
- Example: y = [3
div 0, head (tail [4])]
Tackling the âAwkward Squadâ
- Laziness and side effects are incompatible
- Side effects are important!
- For a long time, this tension was embarrassing to the lazy functional programming community - [will skip earlier solutions that âworked okay for I/O in terms of lazy streamsâ]
- In early 90âs, a surprising solution â the monad -- emerged from an unlikely source (category theory)
- Haskellâs IO monad provides a way of tackling the awkward squad: I/O, imperative state, exceptions, foreign functions, & concurrency.
Monadic I/O: The Key Idea
- IO is a type constructor
- IO t is a type where t is a type
- Think of IO t as describing an âactionâ or âcomputationâ that when performed produces a result of type t
- Now manipulate values of type IO t in your pure lazy language
- Pass them around, combine them, etc.
- With helpful functions and sugar
- But cannot âdo an IO actionâ inside a program
- Only main :: IO a, can be âperformedâ
- By ârunning the programâ
Lecture 8 CSE P505 Autumn 2016 Dan Grossman 25
A helpful picture
- IO is an abstract type constructor, but think of it as:
- âAn actionâ that, when performed, takes âa worldâ and returns âa t and a [new] worldâ
- Thanks to abstraction, there is no way to âget a worldâ, so you canât âstore or copy a worldâ (woah!!) Lecture 8 CSE P505 Autumn 2016 Dan Grossman 26
type IO t = World -> (t, World)
IO t
result :: t
Actions are first class
- Evaluating an IO t produces an action
- Evaluation has no side effects
- Does not perform-the-action, which [probably] has side effects
Lecture 8 CSE P505 Autumn 2016 Dan Grossman 27
Simple I/O
Lecture 8 CSE P505 Autumn 2016 Dan Grossman 28
getChar
Char
putChar
Char ()
getChar :: IO Char putChar :: Char -> IO ()
main :: IO () main = putChar âxâ
Main program is an
action of type IO ()
(and it is performed)
Connection actions
- To read a character and then write it back out, we need to connect two actions
- This is done with the bind combinatorâŚ
putChar
getChar
Char
Bind
- âProvidedâ (as are getChar and putChar are)
- Semantics is exactly âthe compound sequenced actionâ you would expect from the type
(>>=) :: IO a -> (a -> IO b) -> IO b
putChar
Char
getChar
echo :: IO () echo = getChar >>= putChar
Bigger Example
- [Of course in practice, you would provide this as a faster primitive]
- Key points:
- Recursion as usual -
- âMixing inâ regular code that produces actions
Lecture 8 CSE P505 Autumn 2016 Dan Grossman 37
getLine :: IO [Char] getLine = do { c <- getChar ; if c == '\n' then return [] else do { cs <- getLine; return (c:cs) }}
A helpful picture [again]
- IO is an abstract type constructor, but think of it as:
- âAn actionâ that, when performed, takes âa worldâ and returns âa t and a [new] worldâ
- Thanks to abstraction, there is no way to âget a worldâ, so you canât âstore or copy a worldâ (woah!!) - Enforces âsingle pathâ through a sequence of actions Lecture 8 CSE P505 Autumn 2016 Dan Grossman 38
type IO t = World -> (t, World)
IO t
result :: t
Control Structures
- More examples showing how âfirst-class actionsâ can be composed to build your own control structures - Think: treating code [actions] as data and building up compound data that can later be ârunâ - Example use:
Lecture 8 CSE P505 Autumn 2016 Dan Grossman 39
forever :: IO () -> IO () forever a = a >> forever a repeatN :: Int -> IO () -> IO () repeatN n a = if n= then return () else a >> repeatN (n-1) a
repeatN 5 (putChar â#â)
More first-class fun
- Showing general idea of âfirst-class actionsâ lets the programmer define structures of [arbitrary] actions - No need to bake more than >>= and return into the language - Example use:
Lecture 8 CSE P505 Autumn 2016 Dan Grossman 40
sequence :: [IO a] -> IO [a] sequence xs = case xs of [] -> return [] y:ys= do { r <- y; rs <- sequence ys; return (r:rs) }
sequence [getLine, putChar â>â >> return [], getLine]
Growing the IO monad
- The IO monad is âbuilt-inâ to Haskell via main :: IO()
- It is âone-stop shoppingâ for âall the stuff that needs a well- defined sequence when performedâ - a.k.a. âthe sin binâ combined with âthe outside worldâ
- Just a flavor: openFile :: FilePath -> IOMode -> IO Handle hPutStr :: Handle -> String -> IO () hGetLine :: Handle -> IO String hClose :: Handle -> IO () data IORef a -- Abstract type newIORef :: a -> IO (IORef a) readIORef :: IORef a -> IO a writeIORef :: IORef a -> a -> IO ()
So we have an imperative language
So now you could write this count :: (a -> Bool) -> [a] -> IO Int count f xs = do { r <- newIORef 0; help r xs } where help r xs = case xs of [] -> readIORef r | x:xs -> if f x then do { old <- readIORef r; writeIORef r (old+1); help r xs } else help r xs
ButâŚ
- Just because you can write imperative code doesnât mean you should
Lecture 8 CSE P505 Autumn 2016 Dan Grossman 43
count :: (a -> Bool) -> [a] -> Int count f xs = case xs of [] -> 0 | x:xs -> (if f x then 1 else 0)
- count f xs -- previous slideâs count -- :: (a -> Bool) -> [a] -> IO Int -- can get an IO Int with -- return (count f xs)
The Roach Motel -
- âOnce you get in to the IO monad, you canât get outâ
- Bind lets you use a value âin thereâ but âleaves you in thereâ
- Return âgets anything you want in thereâ
- So you find yourself âwanting to cheatâ, looking for a magic_escape :: IO a -> a
- The presence of such a function would âbreak everythingâ because it would have to âperform the actionâ [no other way it could find an a, but then we have side effects in allegedly pure code, which was the whole thing we were trying to avoid ]
Lecture 8 CSE P505 Autumn 2016 Dan Grossman 44
Examples with this problem
- Suppose you want to read some configuration options from a file but treat the values as âpure constantsâ
- This doesnât and shouldnât type-check: readFile :: String->IO String
- Leaves only two options:
- Put all code depending on file contents in IO monad
- Cheat
Lecture 8 CSE P505 Autumn 2016 Dan Grossman 45
configFileContents :: [String] configFileContents = lines (readFile "config") --NO! useOptimization :: Bool useOptimization = elem "optimize" configFileContents
The Cheat Exists (!)
- They call it unsafePerformIO not magic_escape magic_escape :: IO a -> a
- Any code that uses it has an obligation to âknowâ that âit doesnât matterâ - When we perform the IO action - How many times we perform the IO action - Relative order of performing this action vs. other actions [Notice: Reading a read-only, accessible file meets this obligation]
- The operator has a deliberately long to discourage its use
Lecture 8 CSE P505 Autumn 2016 Dan Grossman 46
BTW, It really is a cheat
- You can use unsafePerformIO to circumvent the type system arbitrarily - Exact same issue arises in OCaml without âthe value restrictionâ - OCaml has to avoid this; Haskell can say âunsafePerformIO is unsafeâ
r :: forall a. IORef a -- This is bad! r = unsafePerformIO (newIORef (error "urk"))
cast :: b -> c cast x = unsafePerformIO (do {writeIORef r x; readIORef r })
Implementation
- The compiler front-end and optimizer doesnât know that the IO monad is special - It can be restrained by using an unkown âWorldâ type that is âthreaded throughâ
- Then the back-end code generator can convert the âWorldâ-y code to in-place imperative operations
type IO t = World -> (t, World) -- in compiler front return :: a -> IO a return a = \w -> (a,w) (>>=) :: IO a -> (a -> IO b) -> IO b (>>=) m k = \w -> case m w of (r,wâ) -> k r wâ