2

在 Haskell 代数数据类型中,声明中具有常量值是否合法?换句话说,我可以定义这样的东西:

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

我试图从规范中弄清楚,但语法对我来说并不清楚。

4

1 回答 1

10

不,您不允许这样做(数据类型types,而不是data)。相反,您可以执行以下操作:

data HTTPStatus = HTTPStatus Int String

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

或者,类似的:

data HTTPStatus = BadRequest | NotFound

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

message :: HTTPStatus -> String
message BadRequest = "Bad Request"
message NotFound = "Not Found"
于 2012-12-10T02:38:37.553 回答