Created
June 10, 2014 19:43
-
-
Save ruthenium/72ebdb8905bad924a52e to your computer and use it in GitHub Desktop.
Inheritance and overloading using data Object and w\o typeclasses
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) | |
----------------------------------------------------------------------------------------- | |
{-| Datatype for all the objects -} | |
data Object t = | |
Object { getA :: Int -- common fields for all the objects | |
, setA :: Int -> Object t -- setter example | |
, action1 :: IO () -- generally speaking, action is just a regular object field | |
, objectType :: t | |
} | |
{-| Object factory. | |
It`s supposed that this function will not be used directly, | |
but only for creating a new sub-objects. -} | |
object a action_1 t = | |
Object { getA = a | |
, setA = \a' -> object a' action_1 t | |
, action1 = action_1 | |
, objectType = t | |
} | |
----------------------------------------------------------------------------------------- | |
type Object1 = Object Object1Type | |
data Object1Type = Object1Type -- specific object1-fields only could be here | |
object1 a = object a action_1 Object1Type | |
where | |
action_1 = printf "object1 with field %d \n" a | |
----------------------------------------------------------------------------------------- | |
type Object2 = Object Object2Type | |
data Object2Type = Object2Type | |
object2 o = object (getA o) action_1 Object2Type -- note that we inherit the existing object | |
where | |
action_1 = do -- overloading | |
print "object2 and..." | |
action1 o -- super action | |
-- of course we could also construct the new object1 dynamically: | |
{- object2 a = | |
let o = object1 a | |
a' = getA o | |
action_1 = do | |
print "object2 and..." | |
action1 o | |
in object a' action_1 Object2Type -} | |
----------------------------------------------------------------------------------------- | |
main = do | |
let o1 = object1 10 | |
o2 = object2 o1 | |
action1 o1 | |
action1 o2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment