## root / htools / Ganeti / BasicTypes.hs @ f3f76ccc

History | View | Annotate | Download (2 kB)

1 |
{- |
---|---|

2 | |

3 |
Copyright (C) 2009, 2010, 2011 Google Inc. |

4 | |

5 |
This program is free software; you can redistribute it and/or modify |

6 |
it under the terms of the GNU General Public License as published by |

7 |
the Free Software Foundation; either version 2 of the License, or |

8 |
(at your option) any later version. |

9 | |

10 |
This program is distributed in the hope that it will be useful, but |

11 |
WITHOUT ANY WARRANTY; without even the implied warranty of |

12 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |

13 |
General Public License for more details. |

14 | |

15 |
You should have received a copy of the GNU General Public License |

16 |
along with this program; if not, write to the Free Software |

17 |
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA |

18 |
02110-1301, USA. |

19 | |

20 |
-} |

21 | |

22 |
module Ganeti.BasicTypes |

23 |
( Result(..) |

24 |
, isOk |

25 |
, isBad |

26 |
, eitherToResult |

27 |
, annotateResult |

28 |
) where |

29 | |

30 |
import Control.Monad |

31 | |

32 |
-- | This is similar to the JSON library Result type - /very/ similar, |

33 |
-- but we want to use it in multiple places, so we abstract it into a |

34 |
-- mini-library here. |

35 |
-- |

36 |
-- The failure value for this monad is simply a string. |

37 |
data Result a |

38 |
= Bad String |

39 |
| Ok a |

40 |
deriving (Show, Read, Eq) |

41 | |

42 |
instance Monad Result where |

43 |
(>>=) (Bad x) _ = Bad x |

44 |
(>>=) (Ok x) fn = fn x |

45 |
return = Ok |

46 |
fail = Bad |

47 | |

48 |
instance MonadPlus Result where |

49 |
mzero = Bad "zero Result when used as MonadPlus" |

50 |
-- for mplus, when we 'add' two Bad values, we concatenate their |

51 |
-- error descriptions |

52 |
(Bad x) `mplus` (Bad y) = Bad (x ++ "; " ++ y) |

53 |
(Bad _) `mplus` x = x |

54 |
x@(Ok _) `mplus` _ = x |

55 | |

56 |
-- | Simple checker for whether a 'Result' is OK. |

57 |
isOk :: Result a -> Bool |

58 |
isOk (Ok _) = True |

59 |
isOk _ = False |

60 | |

61 |
-- | Simple checker for whether a 'Result' is a failure. |

62 |
isBad :: Result a -> Bool |

63 |
isBad = not . isOk |

64 | |

65 |
-- | Converter from Either String to 'Result'. |

66 |
eitherToResult :: Either String a -> Result a |

67 |
eitherToResult (Left s) = Bad s |

68 |
eitherToResult (Right v) = Ok v |

69 | |

70 |
-- | Annotate a Result with an ownership information. |

71 |
annotateResult :: String -> Result a -> Result a |

72 |
annotateResult owner (Bad s) = Bad $ owner ++ ": " ++ s |

73 |
annotateResult _ v = v |