Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of an applicative functor?

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]

like image 674
Trident D'Gao Avatar asked Dec 03 '22 17:12

Trident D'Gao


1 Answers

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.

like image 160
leftaroundabout Avatar answered Jan 02 '23 06:01

leftaroundabout