In my previous post, I explained about
read function, which takes a string and convert it to specific type.
Syntax
read "string" :: TypeToConvert
Prelude> read "10.02" :: Double 10.02 Prelude> read "10.02" :: Float 10.02 Prelude> read "10" :: Integer 10 Prelude> read "True" :: Bool True
readLn is similar to read function, only
difference is it gives back whatever type of value you want. You no need to
specify destination type.
Prelude> :t readLn readLn :: Read a => IO a
Sample.hs
factorial n = if n == 0 then 1 else n * factorial (n - 1) main = do putStrLn "What is 5! ?" x <- readLn if x == factorial 5 then putStrLn "You're right!" else putStrLn "You're wrong!"
$ ghc Sample.hs [1 of 1] Compiling Main ( Sample.hs, Sample.o ) Linking Sample ... $ $ ./Sample What is 5! ? 120 You're right! $ $ ./Sample What is 5! ? 123 You're wrong!
No comments:
Post a Comment