문제

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