Difference between revisions of "PFP Laboratory 7"
Jump to navigation
Jump to search
Line 40: | Line 40: | ||
* Create a program, that computes aproximation of PI using random numbers - [https://towardsdatascience.com/estimate-pi-using-random-numbers-8b13a7e8c791 Idea]. | * Create a program, that computes aproximation of PI using random numbers - [https://towardsdatascience.com/estimate-pi-using-random-numbers-8b13a7e8c791 Idea]. | ||
* The number of steps will be defined as program's argument. | * The number of steps will be defined as program's argument. | ||
+ | |||
+ | == Monads == | ||
+ | |||
+ | * Consider you have a type: | ||
+ | <syntaxhighlight lang="Haskell"> | ||
+ | newtype State s a = State { runState :: s -> (s, a) } | ||
+ | </syntaxhighlight> | ||
+ | Make this type the instance of <code>Monad</code> |
Revision as of 11:50, 30 September 2022
Working with files - monad IO
- Create a program that reads a file and number it's lines and writes it on the screen.
For the solution look at: openFile :: FilePath -> IOMode -> IO Handle
The Handle
can used to work with a file. The function to read a content:hGetContents :: Handle -> IO String
At the end, you should close the opened file handle: hClose :: Handle -> IO ()
Alternatively you can use : readFile :: FilePath -> IO String
import System.IO
import Control.Exception
main = do fromHandle <- opf "Read from: " ReadMode
contents <- hGetContents fromHandle
putStr (numberLines contents)
hClose fromHandle
opf :: String -> IOMode -> IO Handle
opf prompt mode = do putStr prompt
name <- getLine
catch (openFile name mode )
(\e -> do putStr ("Can't open "++name++":"++show (e :: IOException) ++"\n")
opf prompt mode)
numberLines::String -> String
numberLines text = let l = lines text
numbered = zip [1..] l
result = [show x ++".\t"++content++"\n" | (x, content)<-numbered]
in concat result
Computing PI
- Create a program, that computes aproximation of PI using random numbers - Idea.
- The number of steps will be defined as program's argument.
Monads
- Consider you have a type:
newtype State s a = State { runState :: s -> (s, a) }
Make this type the instance of Monad