So far we’ve talked a lot about combining functions that both do IO, but we haven’t talked about a common problem: what do you do when you have a function that doesn’t know (or care) about IO, and you want to use it on an IO value?
Let’s think about command line parsing, which can be one of the most common cases where we might run into this situation. Say we wanted to write an application that would add up a list of integers the user provides as command line arguments. We can use the getArgs function from the System.Environment module in base to get a list of all of the command line arguments as a list of strings, but we’ll still need to convert those strings to integers and add them up. Let’s say that we have a function that already knows how to take a list of strings and give us back the sum of them:
| | sumArgs :: [ String ] -> Maybe Int |
We’ll look at the full definition of sumArgs a bit later, but for now let’s just focus on how we could call it with our command line arguments.
The first approach to come to mind is probably the one that we’ve been using so far throughout this chapter. We can use a lambda function to unwrap our IO value so that we can work with it:
| | module SumArguments where |
| | import System.Environment ( getArgs ) |
| | |
| | main :: IO () |
| | main = |
| | getArgs |
| | >>= \ args -> return (sumArgs args) |
| |
This works, but it’s a little bit verbose. We are forced to unnecessarily introduce a new variable, and we’re dedicating a large portion of our code to the ceremony of unwrapping and rewrapping our argument list in an IO action.
Next, you might think that we could make this a little shorter by eliminating our explicit function. We can write this in a shorter, more pointfree style:
| | main :: IO () |
| | main = |
| | getArgs >>= return . sumArgs >>= print |
This is shorter and a little bit easier to read but we’re still not clearly expressing our intention. We use >>= for ordering IO actions, and combining their side effects. Our sumArgs function is a pure function. It doesn’t rely on the state of the real world when we call it, and it doesn’t cause any side effects, so most of what we get from calling >>= is completely superfluous!
| Bind and Return |
|---|
|
| Whenever you see return being used with >>= it’s a sign that you might want to refactor your code. We’ll learn more about the relationship between these two functions in Chapter 9, Introducing Monads , and you’ll be able to understand exactly why this is. Until you’ve finished with that chapter, just remember that whenever you see >>= return it’s a hint that you might want to think about using fmap instead. |
The fmap function comes from the Functor type class, and it helps us solve exactly this problem, by giving us a way to apply a pure function to a value inside of an IO action without having to use >>= . Let’s take a minute to review how map works:
| | λ :type map |
| | map :: (a -> b) -> [a] -> [b] |
| | λ map (+1) [1..5] |
| | [2,3,4,5,6] |
| | λ map show [1..5] |
| | ["1","2","3","4","5"] |
| | λ :type map show [1..5] |
| | map show [1..5] :: [String] |
The fmap function works almost exactly the same way, but it works on all sorts of Functor instances, not just on lists. Let’s look at an example:
| | λ :type fmap |
| | fmap :: Functor f => (a -> b) -> f a -> f b |
| | λ :type fmap (+1) (return 1 :: IO Int) |
| | fmap (+1) (return 1 :: IO Int) :: IO Int |
| | λ fmap (+1) (return 1 :: IO Int) |
| | 2 |
| | λ :type fmap show (return 1 :: IO Int) |
| | fmap show (return 1 :: IO Int) :: IO String |
| | λ fmap show (return 1 :: IO Int) |
| | "1" |
We will talk more about functors in Mapping Functors , but for now we’ll just look at how we can use fmap to make our IO actions more readable.
We can use fmap to make our function more clear by expressing exactly what we’re trying to do:
| | main = |
| | fmap sumArgs getArgs >>= print |
Not only is this code slightly shorter than our previous version, it more clearly communicates what we want to do: get a list of arguments, transform the list using a pure function, and print the transformed list to the screen.
We can use fmap for things other than IO too. In our actual implementation of sumArgs , we can use fmap to avoid having to use an if statement or pattern matching to deal with a Maybe value:
| | import Text.Read ( readMaybe ) |
| | |
| | sumArgs :: [ String ] -> Maybe Int |
| | sumArgs strArgs = |
| | let intArgs = mapM readMaybe strArgs |
| | in fmap sum intArgs |
In this simple function, we are taking a list of strings and using readMaybe , from base ’s Text.Read module, to get back a Maybe [Int] . mapM is a utility function that lets us take lists of monad values like [Maybe a] and [IO a] and convert them to values like Maybe [a] and IO [a] . You’ll learn more about monad values soon .
To keep consistency with other seemingly unpronounceable operators being used for important things in Haskell, the operator (<$>) is a commonly used alias for fmap . We can use it to rewrite our main function:
| | main = |
| | sumArgs <$> getArgs >>= print |
One thing you might notice about this example is how (<$>) here has a nice symmetry with the ($) operator. In both cases you are applying a value to a function. With $ , the value you are applying is a normal Haskell value, and with (<$>) , the value being applied to the function is something like the result of an IO action, or some other functor value.
You’ll notice both fmap and (<$>) are used regularly in Haskell programs. Some code bases adopt a style of preferring one function or the other, but it’s common to mix and match them to maximize readability. Throughout this book we’ll use (<$>) more frequently than fmap . This is a purely stylistic choice, and you are encouraged to try writing your code with both variations of the function to see which style you prefer.