Haskell - How can I use pure functions inside IO functions? -
how can utilize pure functions within io functions? :-/
for example: i'm reading file (io function) , want parse context, string, using pure function referential transparency.
it seems such worlds, pure functions , io functions, separated. how can perchance bridge them?
the simplest way utilize fmap, has next type:
fmap :: (functor f) => (a -> b) -> f -> f b io implements functor, means can specialize above type substituting io f get:
fmap :: (a -> b) -> io -> io b in other words, take function converts as bs, , utilize alter result of io action. example:
getline :: io string >>> getline test<enter> test >>> fmap (map toupper) getline test<enter> test what happened there? well, map toupper has type:
map toupper :: string -> string it takes string argument, , returns string result. specifically, uppercases entire string.
now, let's @ type of fmap (map toupper):
fmap (map toupper) :: io string -> io string we've upgraded our function work on io values. transforms result of io action homecoming upper-cased string.
we can implement using do notation, to:
getuppercase :: io string getuppercase = str <- getline homecoming (map toupper str) >>> getuppercase test<enter> test it turns out every monad has next property:
fmap f m = x <- m homecoming (f x) in other words, if type implements monad, should able implement functor, too, using above definition. in fact, can utilize liftm default implementation of fmap:
liftm :: (monad m) => (a -> b) -> m -> m b liftm f m = x <- m homecoming (f x) liftm identical fmap, except specialized monads, not general functors.
so if want transform result of io action, can either use:
fmap, liftm, or do notation it's 1 prefer. recommend fmap.
haskell io referential-transparency
No comments:
Post a Comment