80 likes | 230 Views
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
E N D
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 shortLinesOnly :: String -> String shortLinesOnly = unlines . filter (\line -> length line < 10) . lines
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
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
Reading a file – simpler import System.IO main4 = do contents <- readFile "haiku.txt" putStr contents putStr "\n" • readFile :: FilePath -> String -> IO()
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
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)