سؤال

Is it legal in a Haskell algebraic datatype to have constant values in the declaration? In other words, can I define something like this:

data HttpStatusCodes = BadRequest "Bad request" 400
                     | NotAuthorized "Not authorized" 401
                     | -- ...

I tried to figure it out from the specification, but the grammar is not clear to me.

هل كانت مفيدة؟

المحلول

No, you are not allowed to do that (data types are types, not data). Instead you can do the following:

data HTTPStatus = HTTPStatus Int String

badRequest, notAuthorized, notFound :: HTTPStatus
badRequest    = HTTPStatus 400 "Bad Request"
notAuthorized = HTTPStatus 401 "Not Authorized"
notFound      = HTTPStatus 404 "Not Found"

or, similar:

data HTTPStatus = BadRequest | NotFound

code :: HTTPStatus -> Int
code BadRequest = 400
code NotFound = 404

message :: HTTPStatus -> String
message BadRequest = "Bad Request"
message NotFound = "Not Found"
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top