Created
November 10, 2015 05:02
-
-
Save motokiee/8a712ad7e829bd207032 to your computer and use it in GitHub Desktop.
独自のデータ型の定義、Eitherの使い方を勉強。HTTPステータスコードと状態の対応表を導き出すコードを簡単な応用で書いてみた。 #CodePiece
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| data LockerState = Taken | Free deriving (Show, Eq) | |
| type Code = String | |
| type LockerMap = Map.Map Int (LockerState, Code) | |
| lockerLookup :: Int -> LockerMap -> Either String Code | |
| lockerLookup lockerNumber map = case Map.lookup lockerNumber map of | |
| Nothing -> Left $ "Locker " ++ show lockerNumber ++ " doesn't exist!" | |
| Just (state, code) -> if state /= Taken | |
| then Right code | |
| else Left $ "Locker " ++ show lockerNumber ++ " is already taken!!" | |
| lockers :: LockerMap | |
| lockers = Map.fromList | |
| [(100, (Taken, "ZD391")), | |
| (101, (Free, "ZD392")), | |
| (118, (Taken, "ZD432")), | |
| (202, (Free, "KU392")) | |
| ] | |
| -- 200を成功, 400を失敗ということにする | |
| data HTTPStatus = Success | Failure deriving (Show, Eq) | |
| type FailureDescription = String | |
| type HTTPStatusMap = Map.Map Int (HTTPStatus, FailureDescription) | |
| httpStatusLookup :: Int -> HTTPStatusMap -> Either String FailureDescription | |
| httpStatusLookup httpStatus map = case Map.lookup httpStatus map of | |
| Nothing -> Left $ "Unrecognized statusCode" | |
| Just (statusCode, description) -> if httpStatus < 400 | |
| then Right $ description | |
| else Left $ description | |
| httpStatusMap :: HTTPStatusMap | |
| httpStatusMap = Map.fromList | |
| [(200, (Success, "Success")), | |
| (201, (Success, "Created")), | |
| (202, (Success, "Accepted")), | |
| (400, (Failure, "Bad Request")), | |
| (401, (Failure, "Unauthorized")), | |
| (404, (Failure, "Not Found")), | |
| (500, (Failure, "Internal Server Error")) | |
| ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment