2012-12-10 104 views
2

它是合法的Haskell的代數數據類型有在聲明常數值?換句話說,我可以定義是這樣的:常量在Haskell代數數據類型

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

我試圖從規範看着辦吧,但語法不是很清楚,我。

+1

不,這是不合法的。它也沒有意義;你想做什麼? – shachaf

+0

昨天晚上發佈了這個問題後,再想一想,我相信我正在努力去做@Zoidberg的回答。 – Ralph

回答

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"