Haskell代数数据类型中的常量

时间:2012-12-10 02:20:37

标签: haskell constants algebraic-data-types

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

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

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

1 个答案:

答案 0 :(得分:10)

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

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"