1 / 8

Haskell

Haskell. Chapter 9. More Input and More Output. Files and Streams Transforming Input Not covered brackets command-line arguments bytestrings. Transforming input. Common pattern: get string from input, transform, output result Use interact main = interact shortLinesOnly

media
Download Presentation

Haskell

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Haskell Chapter 9

  2. More Input and More Output • Files and Streams • Transforming Input • Not covered • brackets • command-line arguments • bytestrings

  3. Transforming input • Common pattern: get string from input, transform, output result • Use interact main = interact shortLinesOnly shortLinesOnly :: String -> String shortLinesOnly = unlines . filter (\line -> length line < 10) . lines

  4. Another example respondPalindromes :: String -> String respondPalindromes = unlines . map (\xs -> if isPalxs then "palindrome" else "not a palindrome") . lines isPal :: String -> Bool isPalxs = xs == reverse xs main2 = interact respondPalindromes

  5. Reading a file import System.IO main3 = do handle <- openFile "haiku.txt" ReadMode contents <- hGetContents handle putStr contents putStr "\n" hClose handle • openFile :: FilePath -> IOMode -> IO Handle • type FilePath = String • data IOMode = ReadMode | WriteMode | AppendMode | ReadWriteMode

  6. Reading a file – simpler import System.IO main4 = do contents <- readFile "haiku.txt" putStr contents putStr "\n" • readFile :: FilePath -> String -> IO()

  7. Randomness • Referential transparency: function given the same parameters twice must return same result • SO, we bring in randomness from outside (like using Unix time stamp for a seed) • Take a random generator, return a random value and new random generator • random : : (RandomGen g, Random a) => g -> (a, g) • Take an integer, return a random generator • mkStdGen :: Int -> StdGen * more random functions in book

  8. Example import System.Random threeCoins :: StdGen -> (Bool, Bool, Bool) threeCoins gen = let (firstCoin, newGen) = random gen (secondCoin, newGen') = random newGen (thirdCoin, newGen'') = random newGen' in (firstCoin, secondCoin, thirdCoin) --threeCoins (mkStdGen 22)

More Related