31

I was looking at the Applicative class within Haskell libraries and stumbled across Alternative.

What is this class good for? A google search did not reveal anything particularly insightful. And it seems to be completely out of place, bundled as it is with the Applicative package.

Could someone please post a possible scenario where you would use this class?

duplode
  • 33,731
  • 7
  • 79
  • 150
Anupam Jain
  • 7,851
  • 2
  • 39
  • 74

2 Answers2

24

It's commonly used with parser combinators. For example, if space is a parser combinator that matches a single whitespace character, many space would be one that would match consecutive whitespace.

I can agree that it's slightly out of place in Control.Applicative, though.

hammar
  • 138,522
  • 17
  • 304
  • 385
  • 21
    Only *slightly* out of place--it's a monoid on `Applicative`s, in the same pattern as `MonadPlus` and `ArrowPlus`, both of which also share a module with the class they're based on. For consistency it "should" have been called `ApplicativePlus` but that's an ugly name. – C. A. McCann Aug 26 '11 at 13:01
  • Okay that explains a lot! Though naming `ApplicativePlus` to `Alternative` isn't such a good thing since the latter has connotations that limit its scope. – Anupam Jain Aug 26 '11 at 17:13
  • @C. A. McCann, I wish you would convert your comment into an answer so I could accept it :) – Anupam Jain Aug 30 '11 at 19:32
  • @Anupam Jain: Eh, I think it's fine as is. hammar already covered the part about where it's actually used and I don't feel like reiterating that to make a complete answer... – C. A. McCann Aug 30 '11 at 20:08
17

Sometimes the <|> operator is quite useful:

foldl1 (<|>) [Nothing, Just 5, Just 3]
-- Just 5
Landei
  • 54,104
  • 13
  • 100
  • 195
  • 1
    Ah that is interesting! In that context <|> is like the short circuit || operator in many imperative languages.. – Anupam Jain Aug 26 '11 at 16:58
  • 3
    You can also do this using `mconcat` with [the `First` monoid](http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:First). This generalizes nicely to [the other `Maybe` monoids](http://byorgey.wordpress.com/2011/04/18/monoids-for-maybe/). – hammar Aug 26 '11 at 18:55
  • 5
    Oh, no, `foldl1` was used somewhere where there is a sensible default (`foldl (<|>) Nothing`). What will you do when your answer crashes? :D – Rotsor Aug 26 '11 at 19:27
  • 2
    @Rotsor or `foldl (<|>) empty` in general, given that `empty` is the identity of `(<|>)` – sam boosalis Jan 31 '15 at 03:41
  • 2
    In general, ```Data.Foldable.asum``` also provides this functionality – abhillman May 19 '15 at 06:06