Friday 29 April 2016

Haskell: return: Convert a to IO a

By using return function we can turn a value into IO action. You can change String to IO String, You can change Int to Io Int etc.,

Prelude> :t return
return :: Monad m => a -> m a


Sample.hs
import Data.Char

getUpper :: String -> IO String
getUpper str = return (map toUpper str)

main = do
    putStrLn "Enter String"
    str <- getLine

    result <- getUpper str
    putStrLn $ "Result is " ++ result

$ ghc Sample.hs
[1 of 1] Compiling Main             ( Sample.hs, Sample.o )
Linking Sample ...
$ 
$ ./Sample
Enter String
Hello Haskell
Result is HELLO HASKELL

Convert list of a to list of IO a

Sample.hs
liftToIO :: [a] -> [IO a]
liftToIO [] = []
liftToIO (x:xs) = (return x) : liftToIO xs

Prelude> :load Sample.hs
[1 of 1] Compiling Main             ( Sample.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> let res1 = [1, 2, 3, 4]
*Main> :t res1
res1 :: Num t => [t]
*Main> 
*Main> let res2 = liftToIO res1
*Main> 
*Main> :t res2
res2 :: Num a => [IO a]




Previous                                                 Next                                                 Home

No comments:

Post a Comment