In this case, a common pattern is to copy the OO concept of casting. For example, instead of having:
class Render a where
render :: a -> IO()
we could have: class Renderable a where
toRender a -> Render
along with: data Render = ...
render :: Render -> IO()
render r = ...
This leads to some noise with needing to put a bunch of toRender functions in a short amount of code, but this problem does not get worse as complexity increases. data GameEntity = GameEntity
{ render :: IO ()
, getPosition :: Point
, setPosition :: Point -> GameEntity
}
makeBall :: Point -> GameEntity
makeBall pos = GameEntity { render = myRender
, getPosition = pos
, setPosition = mySetPos
}
where myRender = {- draw the ball somehow -}
mySetPos newPos = makeBall newPos
{- and similar for makePlayer -}
That means that the rendering code will look like renderAll :: [GameEntity] -> IO ()
renderAll allEntities = mapM_ render allEntities
main = do
pl = makePlayer 1 (0, 5.0)
p2 = makePlayer 2 (10.0, 5.0)
b = makeBall (5.0, 5.0)
{- ... -}
renderAll [p1, p2, b] -- type-checks correctly now
What I've done is used a record type to encode the interface that it's supposed to expose, while hiding exactly what the particular implementations of the interface are. It's also nicely extensible; if I wanted to add in some other kind of entity—say, a turtle—all I'd need to do is add a function like makeTurtle :: Point -> ShellColor -> TurtleDisposition -> GameEntity
and nothing else need be changed.I love how Haskellers (in general, not you in particular) bash OO and then come up with the exact same technique of simulating OO that is used in C (a struct of function pointers). Something which OO languages provide out of the box (interfaces, virtual methods, etc).
Now, let's take this a step further: how would you simulate double-dispatch, or multiple dispatch in Haskell? This is sorely missing from mainstream OO languages.
Really, I think Haskell has a super great object system. It's just (a) not the central conceit and (b) so naturally embedded in the language that you can program for a long time without even noticing it's there.
Codata typically indicates you're looking at an object. In Haskell, due to it being non-terminating as a language, codata and data are unified so most "objects" look identical to their non-object form. You can also notice them by definitions based on eliminators. Automata are a good example
newtype Auto f i o = Auto { run :: i -> f (Auto f i o, o) }
You can also look for objects as ADTs. When you do this you can get a natural embedding of a prototype-based language. (http://www.cs.ox.ac.uk/jeremy.gibbons/publications/adt.pdf) data ADT f = forall st
. ADT { unfold :: st -> f st
, state :: st
}
Here, the internal state type `st` is closed over as an existential value—when you create a new ADT you can pick what st is but the type system then ensures that nobody ever can access that type again. Instead, you have to use the `unfold` elimination form which projects the state into a "class" `f` (represented as a Functor, but that's immaterial) which defines a signature of methods over the abstract state. Auto, from before, is definable this way. data AutoClass st o =
AutoClass { next :: st
, out :: o
}
type Auto = ADT AutoClass
Subtyping occurs naturally with quantified types like the existentially-typed `st` variable or the universally quantified types you see all the time in type signatures. It's a more natural form of subtyping since it's all defined by increasing typeclass bounds. Something like {C} : set of constraints Ci : constraint
------------------------------------------------------
forall a . {C} a => a :> forall a . ({C} a, Ci a) => a
This guarantees that these these two types are good "subtypes on eliminators" which satisfies the Liskov Substitution Principle if not some of the more strict definitions of subtype "niceness".Double/Multiple dispatch is trivially handled in Haskell since polymorphism is solved by an entire Prolog embedded in the type system.
The thing is that Haskell also has initial data, things like finite lists are better thought of as a big tree of constructors
1:(2:(3:(4:(5:[]))))
and then pattern matched upon (defining catamorphisms) sum :: [Int] -> Int
sum (a:bs) = a + sum bs
sum [] = 0
and this pattern is perhaps a little bit emphasized in mainstream Haskell because it sides on the "functional" side of the expression problem. It doesn't mean, though, that Haskell doesn't like the "object oriented" side, but instead that Haskell favors both.As for multiple dispatch, you could always use multi-param type classes:
{-# LANGUAGE MultiParamTypeClasses #-}
class Say a b where say :: a -> b -> IO ()
instance Say Int () where say = putStrLn "Case one"
instance Say Int Int where say = putStrLn "Case two"
which corresponds roughly to the CLOS snippet (defgeneric say (a b))
(defmethod say ((a integer) (b null)) (format t "Case one"))
(defmethod say ((a integer) (b integer)) (format t "Case two"))
I do not believe that there is a way to use the record-based model of objects I showed earlier to do the same thing, but perhaps there is some way that is presently eluding me.It seems like the right answer is the same as it is in OO languages favor composition. Grab the Renderable out of the Foos, Bars, and Bazes then pass that list to the render function. It follows the articles suggestion about think about your types more. Why does anyone think the render function needs the entire player state instead of just the part it needs to render something on the screen?
However, I don’t think this is a good use case. We can get around this problem in a cleaner and safer way by using the type system rather than subverting it.
If I have a more general game with more objects of more types in it, adding each type to the render function is going to get old. In object oriented programming, I'd just call render() on each entry in the list of game objects. But this approach is going to lead me to:
- render each entry in the list of Foo objects
- render each entry in the list of Bar objects
- render each entry in the list of Baz objects
- ...
which doesn't seem to me to work out very well as the game grows more complicated.
(Sorry about all the line breaks - I can't seem to figure out how to get HN to display it right without them.)