[Haskell-cafe] Observer pattern in haskell FRP

Heinrich Apfelmus apfelmus at quantentunnel.de
Tue Nov 27 16:18:17 CET 2012

Nathan Hüsken wrote:
> Hey,
> When writing games in other (imperative) languages, I like to separate
> the game logic from the rendering. For this I use something similar to
> the observer pattern.
> With rendering I mean anything only related to how objects are drawn to
> the screen. Animation state for example.
> On my journey of exploring game programming with haskell (and FRP), I
> wonder what a good way of archiving something similar would be.
> [..]
> So I am wondering: Is there (or can someone think of) a different
> pattern by which this could be archived? Or asked different: How would
> you do it?

Personally, I would recommend is a complete change in perspective.

The main idea of FRP is that it is a method to describe the evolution of 
values in time. What is a game? It's just a picture that evolves in 
time. The user can exert influence on the evolution by clicking certain 
buttons on a mechanical device, but in the end, all he sees is a picture 
that moves.

How to describe picture that moves? Your large picture is probably made 
from smaller pictures, for instance a small picture in the shape of 
something we often call a "spaceship". So, you can implement a game by 
describing the evolution of smaller pictures, and then combine these 
into the description of a larger picture.

Now, the smaller pictures tend to have "hidden state", which means that 
their future evolution depends a lot on the past evolution of the other 
small pictures. In my experience with programming in FRP, it is very 
useful to describe the individual pictures in terms of tiny state 
machines and then connect these state machines via appropriate events 
and behaviors to each other. The essence here is to decouple the 
individual state machines from each other as much as possible and only 
then to use the FRP abstractions to connect and combine them into a 
"large emergent state machine".

(However, it is important to keep in mind that the fundamental 
abstraction is not a state machine, but a time evolution that remembers 
the past. This helps with embracing the new perspective and not 
accidentally fall back to previous ways of thinking. Whether that ends 
up with good code is up to you to find out, but if you decide to apply a 
new perspective, it's best to do it in an extremist way to gain the 
maximum benefit -- this benefit might certainly turn out to be zero, but 
you will never find out if you wet your feet only a little bit.)

Best regards,
Heinrich Apfelmus


More information about the Haskell-Cafe mailing list