Presentation is loading. Please wait.

Presentation is loading. Please wait.

Haskell Chapter 9. More Input and More Output  Files and Streams  Transforming Input  Not covered  brackets  command-line arguments  bytestrings.

Similar presentations


Presentation on theme: "Haskell Chapter 9. More Input and More Output  Files and Streams  Transforming Input  Not covered  brackets  command-line arguments  bytestrings."— 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 Quick Ex: Look up lines, unlines

4 Another example respondPalindromes :: String -> String respondPalindromes = unlines. map (\xs -> if isPal xs then "palindrome" else "not a palindrome"). lines isPal :: String -> Bool isPal xs = 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)


Download ppt "Haskell Chapter 9. More Input and More Output  Files and Streams  Transforming Input  Not covered  brackets  command-line arguments  bytestrings."

Similar presentations


Ads by Google