Download presentation
Presentation is loading. Please wait.
1
Haskell Chapter 9
2
More Input and More Output
Files and Streams Transforming Input Randomness Not covered brackets command-line arguments bytestrings
3
Reading a file – brute force
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
4
Reading a file – simpler
import System.IO main4 = do contents <- readFile "haiku.txt" putStr contents putStr "\n" readFile :: FilePath -> String -> IO() Haiku (from wikipedia) Japanese poetry Essence is “cutting” Traditional has 17 on (syllables) in 3 phrases, with syllables/phrase
5
Transforming input Common pattern*: get string from input transform
output result lines & unlines – convert between lines separated by \n and array Prelude> lines "aa\nbb\nbb" ["aa","bb","bb"] Prelude> unlines ["the","brown","cow","says","moo"] "the\nbrown\ncow\nsays\nmoo\n" *Haskell has a feature named interact that does this. Doesn’t work well on all machines, so we’re not covering.
6
More examples words & unwords Prelude> words "Never trust a llama"
Prelude> unwords ["the","cat","in","the","hat"] "the cat in the hat“ *Main> unwords $ reverse $ words "this is it" "it is this"
7
Another example isPal :: String -> Bool isPal xs = xs == reverse xs *Main> map isPal $ words "civic radar banana racecar apple" [True,True,False,True,False] Review: what’s the purpose of $
8
Randomness Referential transparency: function given the same parameters twice must return same result SO, we bring in randomness from outside (kind of 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
9
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)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.