简体   繁体   中英

Defining an HTTP Multipart Post as a Recursive Datatype in Haskell

I cannot wrap my head around how to define a type in Haskell that represents the recursive nature of an HTTP Multipart MIME POST.

In English, a Post is either a list of Headers along with Content of some type, or it's a list of Headers with Content of another Post. But Content can also be a list of Posts.

So I've defined Header thus:

data Header = Header { hName  :: String
                     , hValue :: String
                     , hAddl  :: [(String,String)] } deriving (Eq, Show)

I guess Content should be something like:

data Content a = Content a | [Post] deriving (Eq, Show)

Obviously, that fails: parse error in constructor in data/newtype declaration: [Post]

I've defined Post as:

data Post = Post { pHeaders :: [Header]
                 , pContent :: [Content] } deriving (Eq, Show)

I'm using Haskell to get a different perspective on my current task, the latest question thereon being here . Just using String for Content , I can parse simple POSTs using Parsec. But the goal is to parse complex Posts.

The link above, and the links found at that question, give the context for my current task. I'm a Haskell hobbyist, so please feel free to offer alternatives to the code I've posted here--I'm not married to it, and I'd love to learn. Ultimately, I'll use F#, unless I am unable to deliver, in which case I'll be forced to use C# and an imperative style. I welcome any wisdom or direction that supports a functional solution!

Your datatypes make sense, your syntax is just wrong:

data Content a = Content a | Posts [Post a] deriving (Eq, Show)

You can name the Posts constructor whatever you like. However, you cannot have something like pContent :: [Content] - since content has a type variable, it must be applied to a type:

data Post a = Post { pHeaders :: [Header]
                   , pContent :: [Content a] } deriving (Eq, Show)

I would say that your approach is idiomatic Haskell.

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