Unformatted text preview:

CS 345 slide 105 Spring 200510 February 2005The do notationIn order to define interactive Haskell programs, weneed a way for input and output actions to alternate—i.e., we need to define IO actions as sequences ofsmaller IO actions.The do notation provides a convenient way• to combine I/O actions in sequence, to makecompound actions• to give names to values delivered by I/O actions,in order to refer to them in subsequent actionsdo expressions can look remarkably like imperativeprograms!An alternative definition of putStrLn using do:> putStrLn :: String -> IO ()> putStrLn s = do putStr s> putChar '\n' --defines do’s typeA definition of putStr using do:> putStr :: String -> IO ()> putStr [] = return ()> putStr (c:cs) = do putChar c; putStr cs--using {;} instead of layoutA function that returns an action which outputs agiven string a given number of times:> putNtimes :: Int -> String -> IO ()> putNtimes n s> = if n < 1> then return ( )> else do putStrLn s> putNtimes (n-1) sCS 345 slide 106 Spring 200510 February 2005Naming input valuesWithin a do expression, values delivered by I/Oactions can be named. The names can then be used insubsequent expressions.Example: an action which reads one line and outputsits reverse:> rev1line :: IO ()> rev1line = do line <- getLine> putStr (reverse line)The “<-” has much the same meaning as in the listcomprehension:The constructpattern <- actionintroduces a new pattern (often just a name)• whose names’ scope is the rest of the do-construct• whose value is the value delivered by actionNote the distinction between <- and = : • getLine • the value delivered by getLineare not the same (they’re not even the same type).Hence a definition such as> rev1line = putStr (reverse getLine)would be a type error.CS 345 slide 107 Spring 200510 February 2005Another way to introduce new names into a do con-struct is to use the constructionlet pattern = expressionwhich introduces a pattern• whose names’ scope is the rest of the do-construct• whose value is the value of the expressionExample:> rev2lines :: IO ()> rev2lines = do line1 <- getLine> line2 <- getLine> let r1 = reverse line1> r2 = reverse line2> putStrLn (r2 ++ r1)> putStrLn (r1 ++ r2)By the way, let can also be used this way in listcomprehensions. For example, instead of[ (sqrt y + 1, sqrt y - 1) | y <- someList ]we can write[ (x+1,x-1) | y <- someList, let x = sqrt y ]Here the name x enables the expression sqrt y to beevaluated only once.CS 345 slide 108 Spring 200510 February 2005Interactive programsAn action which obtains an integer from thekeyboard:> getInt :: IO Int> getInt => do s <- getLine> case reads s of> [(n,"")] -> return n> _ -> do putStrLn "bad integer!"> getIntAn action which reads integers from successive linesuntil 0 is read, and delivers their sum:> sumInts :: IO Int> sumInts = do n <- getInt> if n = = 0 then return 0> else do m <- sumInts> return (n+m)A program that outputs a greeting, reads someintegers, and prints their sum:> sumInter :: IO ()> sumInter> = do putStr "Enter integers, one per line, "> putStr "ending with 0.\n"> sum <- sumInts> putStr "Sum = "> print sumCS 345 slide 109 Spring 200510 February 2005MonadsThe type-constructor IO is one instance of a class oftype constructors called monads.Informally, what monadic types provide is a means ofhiding details we don’t need —and prefer not— to beconcerned with. Monadic types are thus a kind ofabstract data type.The IO monad hides such details as the state of theinput stream, while allowing values to be extractedfrom it in ways that preserve referential transpar-ency.What distinguishes monadic types from otherabstract data types is that every monadic type mprovides a means (represented by the do construct) of• defining m-values by sequential composition of m-values• introducing values of other types into an m-sequence (return)• extracting values of other types from an m-sequence (name <- ...)The monadic nature of IO actions is what enables thestate of the input stream to be passed from one IOaction to the next without ever being visible in theHaskell code.CS 345 slide 110 Spring 200510 February 2005Parsing: another practical application of monads.Parsing is a process of recognition, and a parser is arecognizer.• High-level parsers recognize items such asexpressions, terms, and factors.• Low-level parsers recognize items suchas ‘(’, ‘+’, or individual letters or digits.In Haskell, high-level parsers are built from low-levelparsers using a toolkit of parser-combining func-tions, or combinators.A parser examines the leading edge of a string andeither succeeds or fails.• If it succeeds, it delivers a value derived from theitem it has recognized (sometimes this is the itemitself).• If it fails, it delivers nothing.(In this implementation of parsers, what they deliveris returned in a list; delivering “nothing” meansreturning an empty list. Defining parsers as monadshides these details, and enables us to focus on what isdelivered, rather than on how it is delivered.)The nature of the value delivered by a parser when itsucceeds depends on the purpose for which theparser is designed. Examples:• an expression parser could deliver the expres-sion’s value, or its postfix representation•a numeral parser could deliver the numeral’svalue•a name parser could deliver the name’s spelling• a comment parser could deliver ()CS 345 slide 111 Spring 200510 February 2005The type-constructor Parser is a monad defined sothatParser ais a parsing action which, applied to a String, attemptsto recognize something at the String’s leading edge.The type variable a is the type of the values theparser delivers when it succeeds.(Unlike IO, Parser is defined as a monad purely forconvenience; here there’s no risk that referentialtransparency could be compromised.)Two elementary parsers:item :: Parser CharWhen item is used to parse a string (c:_) itdelivers c; item fails only when it is appliedto [].mzero :: Parser aWhen mzero is used to parse any String, itfails.Two parser-generating functions:return :: a -> Parser aWhen (return x) is used to parse a string, itdelivers x.sat :: (Char -> Bool)


View Full Document

UT CS 345 - Lecture Slides

Download Lecture Slides
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture Slides and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture Slides 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?