在 snap 中使用 reader monad(或者在 snap 中使用 monad 转换器)
有人可以展示如何在 reader monad 中使用 snap monad 吗? Monad 转换器让我很困惑。 (或者,我很乐意接受关于 monad 转换器的教程建议,以及如何看到光明并最终理解它们。)
编辑:哎呀;忘记具体说明我实际上想要做什么,而不是寻求特定事情的帮助。战略,而不是战术。我特别想在所有处理程序之间共享数据库连接/池,而不必在指定路由时显式传递该数据库连接/池。读者单子似乎是实现这一目标的方法。
Can someone show how to use the snap monad inside the reader monad? Monad transformers confuse me. (Alternatively, I will gladly accept suggestions of tutorials about monad transformers, and ways to see the light and finally grok them.)
Edit: Oops; forgot to specify what I'm actually trying to do, instead of asking for help with a specific thing. Strategy, not tactics. I specifically want to share a database connection/pool amongst all handlers, without having to explicitly pass that database connection/pool when specifying routes. It seems that the reader monad would be the way to accomplish that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Snap 具有 ApplicationState 类型,允许您打包所需的任何应用程序范围资源(数据库连接、模板引擎等)。
它位于生成的文件 Application.hs 中,默认情况下,HeistState 和 TimerState 包含在 ApplicationState 中。您只需将数据库连接放在那里,就可以在 Snap 应用程序中的任何位置使用它。
Snap has ApplicationState type that allows you package whatever application wide resources you need (db connections, template engines etc.)
It is located in generated file Application.hs and by default has HeistState and TimerState included into ApplicationState. You can just put your db connection there and it will be available from anywhere in your Snap application.
如果您不害怕使用 GHC 特定的扩展,这里有一个简单的 monad 转换器方法:
您现在可以使用
ask
和local
来访问读取器数据。要在 Snap monad 中运行操作,您需要将其“提升”到新的 monad 中。不过,您可能更喜欢较短的名称。所以,也许只是
snap
。If you're not afraid to use GHC-specific extensions, here's the no-frills approach to monad transformers:
You can now use
ask
andlocal
to access the reader data. To run an action in theSnap
monad, you need to "lift" it into your new monad.You may prefer a shorter name, though. So, maybe just
snap
.假设 snap monad 来自 http ://hackage.haskell.org/packages/archive/snap-core/0.4.0/doc/html/Snap-Types.html... Snap 是一个 monad (不是 monad 转换器),所以你无法在任意 monad 内运行它。如果您需要的话,您可以使用
ReaderT
转换器将 Reader 功能嵌入到 Snap 中。runSnap 的类型
告诉我们它在 Iteratee ByteString IO monad 中运行。 Reader monad 不允许您执行 IO 或迭代输入流,因此您无法在 Reader monad 中运行 Snap 计算。
如果您解释您想要实现的目标,有人可能会提出实现它的方法。
Assuming the snap monad is from http://hackage.haskell.org/packages/archive/snap-core/0.4.0/doc/html/Snap-Types.html... Snap is a monad (not a monad transformer), so you cannot run it inside an arbitrary monad. You could use the
ReaderT
transformer to embed Reader functionality inside Snap, if that's what you want.The type of
runSnap
iswhich tells us that it runs in an
Iteratee ByteString IO
monad. A Reader monad does not let you do IO or iterate over an input stream, so you cannot run a Snap computation in a Reader monad.If you explain what you want to accomplish, someone may be able to suggest a way to achieve it.