简体   繁体   English

Haskell代数数据类型中的常量

[英]Constants in Haskell algebraic datatypes

Is it legal in a Haskell algebraic datatype to have constant values in the declaration? 在Haskell代数数据类型中,在声明中具有常量值是否合法? 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM