T
T
tottot2014-05-24 19:57:32
Haskell
tottot, 2014-05-24 19:57:32

Explain code in Haskell

could you explain to me the specific Hakell code

{-# LANGUAGE OverloadedStrings #-}
import Data.Conduit
import Network.HTTP.Conduit
import qualified Data.Conduit.Binary as CB
import qualified Data.ByteString.Char8 as BS
import Control.Monad.Trans

main = do
  manager <- newManager def
  req <- parseUrl "http://localhost:8080/api/v1.0/streams/counter"
  let headers = requestHeaders req
      req' = req {
          requestHeaders = ("Accept", "application/x-json-stream") :
                           headers
        }
  runResourceT $ do
    res <- http req' manager
    responseBody res $$+- CB.lines =$ counterSink

counterSink :: Sink BS.ByteString (ResourceT IO) ()
counterSink = do
  md <- await
  case md of
    Nothing -> return ()
    Just d -> do
      liftIO $ BS.putStrLn "--------"
      liftIO $ BS.putStrLn d
      counterSink

I will be very grateful. hard to understand haskell

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
malerix, 2014-05-25
@tottot

I'm not good at this, but I'll try to comment:
First, modules from libraries are imported:
conduit - for working with data streams (if I'm not mistaken, they used iteratee for these purposes before);
http-conduit - "extension" for Network.HTTP to work with this conduit;
Binary, ByteString - I think it's understandable - for data type conversions.
Create a connection manager from default settings
Create a request:
Then we complete the headers in the request:

let headers = requestHeaders req
      req' = req {
          requestHeaders = ("Accept", "application/x-json-stream") :
                           headers
        }

"Safely" (here I can hardly describe exactly, it's better to read the documentation ) the monad is "launched". Something like try, only with thread safety and other things.
runResourceT $ do
    res <- http req' manager
    responseBody res $$+- CB.lines =$ counterSink

Here we hang ( =$ ) the "counterSink" handler, which will wait for all data ( $$+- ) to be received, and already in the form of lines ( CB.lines ).
The counterSink function waits for data, and if it arrives, prints it to stdout:
--------
<data>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question