Created
June 4, 2014 19:33
-
-
Save ruthenium/98a4c7147a7cd2dad02b to your computer and use it in GitHub Desktop.
Simple Inheritance and overloading using typeclasses in haskell
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
import Text.Printf (printf) | |
----------------------------------------------------------------------------- | |
{- interface: -} | |
data BaseObject = BaseObject { baseObjectA :: Int } -- the top-level object | |
class WithInheritedActions a where | |
-- inherited actions: | |
action1 :: a -> IO () | |
--action2 :: a -> Foo | |
-- getters and setters for common fields: | |
getA :: a -> Int | |
setA :: a -> Int -> a | |
{- we make the top-level object an instance of subclass just to make | |
the usage in subobjects easier. -} | |
instance WithInheritedActions BaseObject where | |
action1 a = print "BaseObject" | |
getA = baseObjectA | |
setA a v = a { baseObjectA = v } | |
----------------------------------------------------------------------------- | |
{- usage examples: -} | |
data Object1 = Object1 { object1Base :: BaseObject } -- simple usage example. | |
instance WithInheritedActions Object1 where | |
action1 a = printf "object1 with param=%d\n" $ getA a | |
getA = getA . object1Base | |
setA a v = a {object1Base = setA (object1Base a) v} | |
{- time to show some overloading: -} | |
data Object2 = Object2 { object2Base :: BaseObject } | |
instance WithInheritedActions Object2 where | |
action1 a = print "object2" | |
getA = getA . object2Base | |
setA a v = a {object2Base = setA (object2Base a) v} | |
data Object3 = Object3 { object3Base :: Object2 } | |
instance WithInheritedActions Object3 where | |
action1 a = do | |
print "object 3, and... " | |
action1 $ object3Base a | |
getA = getA . object3Base | |
setA a v = a {object3Base = setA (object3Base a) v} | |
----------------------------------------------------------------------------- | |
{- now the one can do: -} | |
main = do | |
let | |
o1 = Object1 $ BaseObject 12 | |
o2 = Object2 $ BaseObject 0 | |
o3 = Object3 $ o2 | |
action1 o1 | |
action1 $ setA o1 24 | |
action1 o2 | |
action1 o3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment