public
Created

  • Download Gist
Chainable.hs
Haskell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
module Chainable (
(==?), (/=?),
(<?), (<=?), (>?), (>=?),
isJust
) where
 
import Data.Maybe (isJust)
import Control.Monad (liftM, liftM2)
 
infixl 4 ==?
infixl 4 /=?
(==?),(/=?) :: (Eq b) => Maybe b -> b -> Maybe b
Just x ==? y = if x == y then Just y else Nothing
Nothing ==? _ = Nothing
Just x /=? y = if x /= y then Just y else Nothing
Nothing /=? _ = Nothing
 
infixl 4 <?
infixl 4 >?
infixl 4 <=?
infixl 4 >=?
(<?),(>?),(<=?),(>=?) :: (Ord b) => Maybe b -> b -> Maybe b
Just x <? y = case compare x y of LT -> Just y ; _ -> Nothing
Nothing <? _ = Nothing
Just x >? y = case compare x y of GT -> Just y ; _ -> Nothing
Nothing >? _ = Nothing
Just x <=? y = case compare x y of GT -> Nothing; _ -> Just y
Nothing <=? _ = Nothing
Just x >=? y = case compare x y of LT -> Nothing; _ -> Just y
Nothing >=? _ = Nothing
 
-- convenience instance so that we don't need to do
-- Just 0 <=? x <? 100
instance Num a => Num (Maybe a) where
(+) = liftM2 (+)
(*) = liftM2 (*)
(-) = liftM2 (-)
negate = liftM negate
abs = liftM abs
signum = liftM signum
fromInteger = Just . fromInteger

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.