Last active
August 29, 2015 14:13
-
-
Save kgadek/6a919ececea371de5552 to your computer and use it in GitHub Desktop.
Cool polymorphism
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
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, GADTs, RankNTypes #-} | |
class HasX a b | a -> b where getX :: a -> b | |
data Point2 where | |
Point2 :: Int -> Int -> Point2 | |
data Point3 where | |
Point3 :: Float -> Float -> Float -> Point3 | |
instance HasX Point2 Int where getX (Point2 x _) = x | |
instance HasX Point3 Float where getX (Point3 x _ _) = x | |
--myIf :: (Show a1, Show b1, Show c1, | |
-- HasX a a1, HasX b b1, HasX c c1 | |
-- ) => Bool -> a -> b -> c1 | |
--myIf bool a b | bool = getX a | |
-- | otherwise = getX b | |
--example = show res | |
-- where | |
-- res = myIf True (Point2 1 2) (Point3 0.0 0.1 0.2 | |
myIf :: (Show a1, Show b1, | |
HasX a a1, HasX b b1 | |
) => Bool | |
-> a | |
-> b | |
-> (forall c c1. (HasX c c1, Show c1) => c | |
-> r) | |
-> r | |
myIf True a b k = k a | |
myIf False a b k = k b | |
example = myIf False (Point2 1 2) (Point3 0.0 0.1 0.2) (show.getX) |
With help of @Saizan:
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, GADTs, RankNTypes #-}
class HasX a b | a -> b where getX :: a -> b
data Point2 where
Point2 :: Int -> Int -> Point2
data Point3 where
Point3 :: Float -> Float -> Float -> Point3
instance HasX Point2 Int where getX (Point2 x _) = x
instance HasX Point3 Float where getX (Point3 x _ _) = x
myIf :: (Show a1, Show b1,
HasX a a1, HasX b b1
) => Bool
-> a
-> b
-> (forall c c1. (HasX c c1, Show c1) => c
-> r)
-> r
myIf True a b k = k a
myIf False a b k = k b
example = myIf False (Point2 1 2) (Point3 0.0 0.1 0.2) (show.getX)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This results in