简体   繁体   English

是否可以在Haskell中构建Restful API,而无需使用Reader / Writer / State Monad或Monad Transformer

[英]Is it possible to build a Restful API in Haskell without using Reader/Writer/State Monad or Monad Transformer

As a beginner, I feel Reader/Write/State Monad is difficult to understand. 作为一个初学者,我觉得阅读器/写入/状态Monad很难理解。 And Monad Transformers is even more difficult. 而Monad变形金刚则更加困难。 I don't see the usage of them in other languages, which makes me a bit hard to relate them to my existing web development experience. 我看不到它们在其他语言中的用法,这使我很难将它们与我现有的Web开发经验联系起来。

Is it possible to build a Restful API that talks to Postgres in beginner-friendly Haskell? 是否有可能在对初学者友好的Haskell中构建与Postgres对话的Restful API? Meaning without using this advanced stuff like Monads/Monad Transformers. 无需使用诸如Monads / Monad Transformers这样的高级内容的含义。

It is generally possible to write Haskell programs without dealing with monad transformers or various monads like Reader, Writer, and State. 通常可以编写Haskell程序而无需处理monad转换器或诸如Reader,Writer和State的各种monad。 The one monad you cannot avoid is IO. 您无法避免的一个monad是IO。

For example, look at this sample code from the documentation for Warp : 例如,从Warp的文档中查看以下示例代码:

app :: Application
app req respond = bracket_
    (putStrLn "Allocating scarce resource")
    (putStrLn "Cleaning up")
    $ respond $ responseStream status200 [] $ \write flush -> do
        write $ byteString "Hello\n"
        flush
        write $ byteString "World\n"

It's all just made out of function calls and the IO monad. 这些都是由函数调用和IO monad组成的。 You are free to write your code in this style too… and parts of it will look very similar to the same code you would write in some other language. 您也可以自由地以这种样式编写代码……它的某些部分看起来与使用其他语言编写的相同代码非常相似。 Basically, you write a function that takes two arguments: one is the HTTP request, and the other argument is something you can use to write a response. 基本上,您编写了一个带有两个参数的函数:一个是HTTP请求,另一个是可以用来编写响应的参数。 This is just the same way that WSGI works in Python, or net.http in Go. 这与WSGI在Python或Go.net中的net.http工作的方式相同。

If at some point you decide that monad transformers are useful and will make your code simpler, you can always try that out later. 如果在某个时候您认为monad转换器是有用的并且可以使您的代码更简单,那么以后总是可以尝试一下。 But they are not necessary by any means. 但是它们绝不是必需的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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