Designing a purely functional web application handler in Scala
In a webapplication a handler typically consists of a function taking a Request and return a Response:
val handler:Request=>Response
What would the the "most pure" functional approach if handler tak开发者_开发技巧es some parameters from the Requests, changes some shared mutable state (for example a database), and then return a Response?
There's no such thing as "most pure", either the function performs side effects or not (you can discriminate between types of side effects, but that's another topic). So, if you need state in a pure function the only way is to pass the "before" state as parameter and return the "after" state, for example:
val handler : Request => State => (Response, State)
This is similar to the IO monad in Haskell. It can be defined like this in Scala:
type IO[A] = State => (A, State)
So the above can be written more tersely as:
val handler : Request => IO[Response]
What would the the "most pure" functional approach if handler takes some parameters from the Requests, changes some shared mutable state (for example a database), and then return a Response? How would this be done in Haskell?
It would be handled monadically, e.g.
handler :: Request -> Web Response
the type indicates the handler will receive a Request
value, and do some action in a Web
computational environment (containing things like the shared database), before returning a Response
.
If you squint, you can actually see such a model in a production Haskell web server, snap. The effects all occur in the Snap
monad.
Edit: I see you changed your question to not include a Haskell answer. Nonetheless, there is a rich amount of working on designing good web systems in Haskell. Looking at Snap or Yesod is a place to start.
精彩评论