Haskell - How can I use pure functions inside I / O functions?

How can I use pure functions inside I / O functions ?: - /

For example: I am reading a file (I / O function), and I want to analyze its context, string, using a pure function with referential transparency.

It seems that such worlds, pure functions, and I / O functions are separated. How can I hide them?

+5
source share
4 answers

The easiest way is to use fmapone that has the following type:

fmap :: (Functor f) => (a -> b) -> f a -> f b

IOimplements Functor, which means that we can specialize the above type, substituting IOfor f, to get:

fmap :: (a -> b) -> IO a -> IO b

, , a b s IO. :

getLine :: IO String

>>> getLine
Test<Enter>
Test
>>> fmap (map toUpper) getLine
Test<Enter>
TEST

? , map toUpper :

map toUpper :: String -> String

String a String. , .

fmap (map toUpper):

fmap (map toUpper) :: IO String -> IO String

IO. IO, .

do, :

getUpperCase :: IO String
getUpperCase = do
    str <- getLine
    return (map toUpper str)

>>> getUpperCase
Test<Enter>
TEST

, :

fmap f m = do
    x <- m
    return (f x)

, - Monad, Functor , . , liftM fmap:

liftM :: (Monad m) => (a -> b) -> m a -> m b
liftM f m = do
    x <- m
    return (f x)

liftM fmap, , .

, IO, :

  • fmap,
  • liftM,
  • do

, . fmap.

+8

liftM Control.Monad.
, ( ghci, IO Monad)

$ import Control.Monad -- to emerge liftM
$ import Data.Char     -- to emerge toUpper
$ :t map to Upper -- A pure function
map toUpper :: [Char] -> [Char]
$ :t liftM 
liftM :: Monad m => (a1 -> r) -> m a1 -> m r
$ liftM (map toUpper) getLine 
+2

. :

", , ? do {x < - ioFunc; return (pureFunc x)} "

:

import System.IO  
import Data.List

getFirstPart line Nothing = line
getFirstPart line (Just index) = fst $ splitAt index line 

eliminateComment line = 
 getFirstPart line $ elemIndex ';' line

eliminateCarriageReturn line =
 getFirstPart line $ elemIndex '\r' line

eliminateEntersAndComments :: String -> String  
eliminateEntersAndComments text =
 concat $ map mapFunction $ lines text
 where
  mapFunction = (++ " ") . eliminateCarriageReturn . eliminateComment

main = do {
 contents <- readFile "../DWR-operators.txt"; 
 return (eliminateEntersAndComments contents)
}
+1

:

main = do
  val <- return (purefunc)

return , val.

0
source

All Articles