Created
May 16, 2021 08:05
-
-
Save ludat/78038d638783afe081b1b65744c1d56c to your computer and use it in GitHub Desktop.
Evil `a > b > c` with haskell type madness
This file contains 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 Comparable a | |
-- = Success a | |
-- | Failure | |
-- class Comp a b | a -> b where | |
-- type Result a :: Type | |
-- (.<) :: a -> b -> Result a | |
-- instance Comp (Comparable Int) Int where | |
-- type Result (Comparable Int) = Bool | |
-- (Success a) .< b = a < b | |
-- (Failure) .< _ = False | |
-- instance Comp Int Int where | |
-- type Result Int = Comparable Int | |
-- a .< b = if a < b then Success b else Failure | |
-- data Comp a = GreaterThan a (Comp a) | L a deriving Show | |
-- (.>) :: Comp Int -> Int -> Comp Int | |
-- a .> b = GreaterThan b a | |
-- infixl .> | |
-- tobool :: Comp Int -> Bool | |
-- tobool c = | |
-- case go c of | |
-- Just _ -> True | |
-- Nothing -> False | |
-- where | |
-- go :: Comp Int -> Maybe Int | |
-- go (GreaterThan b ci2) = do | |
-- a <- go ci2 | |
-- if a > b | |
-- then pure b | |
-- else Nothing | |
-- go (L n) = pure n | |
-- >>> tobool $ L 3 .> 2 .> 0 | |
-- True | |
-- >>> tobool $ L 1 .> 1 .> 1 | |
-- False | |
data CompResult a = FalseComp | Comparison a a | |
deriving Show | |
class Comp c where | |
type T c :: Type | |
leftSide :: c -> T c | |
rightSide :: c -> T c | |
isfalse :: c -> Bool | |
instance Comp Int where | |
type T Int = Int | |
leftSide = id | |
rightSide = id | |
isfalse _ = False | |
-- TODO: replace `Int` with `a` | |
instance Comp (CompResult Int) where | |
type T (CompResult Int) = Int | |
-- leftSide FalseComp = FalseComp -- Oops, it's not an `Int`! | |
leftSide (Comparison x _) = x | |
-- rightSide FalseComp = FalseComp | |
rightSide (Comparison _ y) = y | |
isfalse (Comparison _ _) = False | |
isfalse FalseComp = True | |
(.<) :: (Comp a, Comp b, T a ~ T b, Ord (T a)) => a -> b -> CompResult (T a) | |
x .< y | |
| (isfalse x) || (isfalse y) = FalseComp | |
| (rightSide x) < (leftSide y) = Comparison (leftSide x) (rightSide y) | |
| otherwise = FalseComp |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment