user2879704
user2879704

Reputation:

Parsing a http Post request using ctor, <$

-- file: ch16/HttpRequestParser.hs
p_request :: CharParser () HttpRequest
p_request = q "GET" Get (pure Nothing)
        <|> q "POST" Post (Just <$> many anyChar)
  where q name ctor body = liftM4 HttpRequest req url p_headers body
            where req = ctor <$ string name <* char ' '
        url = optional (char '/') *>
              manyTill notEOL (try $ string " HTTP/1." <* oneOf "01")
              <* crlf

The above snippet is meant for parsing a http request..

variable ctor is seen on the left side and the right side,

q name ctor body = liftM4 HttpRequest req url p_headers body  --- ctor assigned a value
       where req = ctor <$ string name <* char ' '            --- ctor used as a function

And the variable name is as well seen on LHS and RHS.

And <$> maps all list elements to a constant value. In this context,

ctor <$ string name <* char ' '

what does it return?

Upvotes: 0

Views: 70

Answers (1)

ErikR
ErikR

Reputation: 52039

Specific examples of the expression ctor <$ string name <* char ' ' are:

Get <$ string "GET" <* char ' '

and

Post <$ string "POST" <* char ' '

Get and Post are constructors for the GET and POST HTTP verbs. They probably come from a data definition like:

data HttpVerb = Get | Post | Head | ...

The <$ operator is defined to be fmap . const (see here) and has type:

<$ :: a -> f b -> f a

In other words, it simply wraps up a in the functor but after evaluating its second argument f b. Note that you normally see <$> used here and that the value b is ignored. The absence of the > in the operator serves to indicate that the value to the right is ignored. Similarly for the <* operator.

So, the parser computation Get <$ string "GET" <* char ' ' returns f Get (where f is the parser functor) but only if string "GET" and char ' ' succeed.

The equivalent monadic expression is:

do string "GET"; char ' '; return Get

Upvotes: 2

Related Questions