Skip to content

Instantly share code, notes, and snippets.

@rampion
Created February 19, 2012 20:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rampion/1865644 to your computer and use it in GitHub Desktop.
Save rampion/1865644 to your computer and use it in GitHub Desktop.
{-# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment