Can anyone share a good real life situation when a function with the following signature would be useful?
f (a -> b) -> f a -> f b
I can't really see where I would need something like the schoolbook examples from learn-you-a-haskell [(+),(*)] <*> [1,2] <*> [3,4]
Applicatives can be used for lots of stuff that you might also do with a monad, but that don't really need the stronger features of that class. (More precisely, whenever the “shape” of the functor doesn't depend on values within, then Applicative
is sufficient.) For instance, an action like
foobar :: IO [String]
foobar = do
fooTxt <- readFile "foo.txt"
barTxt <- readFile "bar.txt"
return $ zip (lines fooTxt) (lines barTxt)
could as well be written
foobar = zip <$> (lines <$> readFile "foo.txt")
<*> (lines <$> readFile "bar.txt")
In this case, that makes it merely a tad shorter, but in other cases it may also improve performance (because Applicative
is less general, more optimisations are possible) or allow you to make code more generic than when you use the Monad
interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With