简体   繁体   中英

Are applicative functors composed with the applicative style really independent?

I've come to understand functors, applicative functors, and monads as follows:

  • Functors: computations that can be mapped over.
  • Applicative functors: independent computations whose results can be combined together.
  • Monad: (possibly, but not necessarily) dependent computations that can be chained.

However, there is something about Applicative that conflicts with my understanding... Here is a Haskell example of a parser defined on the basis of more basic parsers using the applicative style:

(,) <$> parseName <*> parseEmail

The effects of the two parsers, parseName and parseEmail , are not independent, because they both consume tokens from the same input stream, eg

Jubobs jubobs@jubobs.io

parseEmail can only consume what hasn't been consumed by parseName . How, then, can the two computations be said to be independent?

The independence here is not saying that one computation cannot detect what other computations have been run - that is, it's not supposed to be the case that parseName has no effect on parseEmail. Rather, you cannot make use of the applicative value (the name parsed by parseName) to choose what applicative computation to run next: you can only ever parse a generic email, rather than, say, parsing an email address while checking that it does not contain the parsed name.

Another way of putting it is that if you use only applicative functions, the overall "shape" of your computation is predetermined ahead of time: you will always parse a name, followed by an email address. If you used monadic functions, you could make decisions about what to parse next based on the results of previous parses, letting you change the shape of your computation as it is running.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM