简体   繁体   中英

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. And Monad Transformers is even more difficult. 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.

Is it possible to build a Restful API that talks to Postgres in beginner-friendly Haskell? Meaning without using this advanced stuff like Monads/Monad Transformers.

It is generally possible to write Haskell programs without dealing with monad transformers or various monads like Reader, Writer, and State. The one monad you cannot avoid is IO.

For example, look at this sample code from the documentation for 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. 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. This is just the same way that WSGI works in Python, or net.http in Go.

If at some point you decide that monad transformers are useful and will make your code simpler, you can always try that out later. But they are not necessary by any means.

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