在 Scala 中设计纯功能性 Web 应用程序处理程序
在 Web 应用程序中,处理程序通常由一个接受请求并返回响应的函数组成:
val handler:Request=>Response
如果处理程序从请求中获取一些参数,更改一些共享的可变状态,那么“最纯粹”的功能方法是什么(例如数据库),然后返回一个响应?
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 takes some parameters from the Requests, changes some shared mutable state (for example a database), and then return a Response?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不存在所谓“最纯粹”的东西,无论该函数是否执行副作用(您可以区分副作用的类型,但这是另一个主题)。因此,如果您需要纯函数中的状态,唯一的方法是将“之前”状态作为参数传递并返回“之后”状态,例如:
val handler : Request =>状态=> (Response, State)
这类似于 Haskell 中的 IO monad。在 Scala 中可以这样定义:
type IO[A] = State => (A, State)
因此上面的内容可以更简洁地写为:
val handler : Request => IO[响应]
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]
它将以单子方式处理,例如,
类型指示处理程序将接收
Request
值,并在Web
计算环境(包含共享数据库等内容)中执行某些操作,在返回响应
之前。如果你眯着眼睛,你实际上可以在生产 Haskell Web 服务器中看到这样的模型, 快照。这些效果都发生在
Snap
monad 中。编辑:我看到您更改了问题以不包含 Haskell 答案。尽管如此,在 Haskell 中设计良好的 Web 系统方面还有大量工作要做。查看 Snap 或 Yesod 是一个起点。
It would be handled monadically, e.g.
the type indicates the handler will receive a
Request
value, and do some action in aWeb
computational environment (containing things like the shared database), before returning aResponse
.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.