[Haskell-cafe] Observer pattern in haskell FRP

Nathan Hüsken nathan.huesken at posteo.de
Tue Dec 11 16:08:43 CET 2012


Am 10.12.2012 16:56, schrieb Ertugrul Söylemez:
> Nathan Hüsken <nathan.huesken at posteo.de> wrote:
>
>> I put a pseudo C++ example below the mail. I use the terms "model" and
>> "view" for the game logic and rendering respectively.
>> The example is a little different. Asteroids explode when they
>> collide. The moment asteroids explode, they are removed from the model
>> (the game logic) while in the view (rendering) they still exist until
>> the explosion animation is over.
>>
>> As you said, this basically is sending messages from the Model (in the
>> observer pattern called Observable) to the view (Observer). The main
>> difficulty I have is how to send the messages from the correct model
>> to the correct view.
>> In C++ this is done by keeping pointers.
>> Simply assigning IDs would work, but than I would have to always pass
>> a map from the model to the view, and I feel like (also I have little
>> experience with this), that this approach is not very scalable.
> Actually it is very scalable, as the same map is passed to every object.
> It can even live in the underlying monad, which means that you could
> even use a mutable vector, if you wish; however, I don't recommend that.
>
> Remember that a map is immutable and shared, so passing the same map to
> multiple objects is in fact the same as passing a pointer in C++.
> Lookups in and updates to the map are of logarithmic complexity, so this
> scales well.  Only doubling the number of nodes actually adds one full
> step to lookups and updates.
>
> If you're dealing with millions of objects you may want to use the
> vector solution mentioned earlier.  This requires an imperative
> underlying monad, but you would get about the same speed as in C++.
>
I might just not be used enough to functional data structures, "Purely 
functional data structures" is on my reading list :).

I was thinking, in the asteroids example the only reason why the view 
needs more input than the models output, is that it needs to be informed 
of creation and destruction of asteroids.

So, in the model one could habe a signal

asteroidsModel :: Signal Input [Just AsteroidModel]

which outputs "Nothing" for asteroids that have been destroyed.
Then, in the view this would be taken for as input for

asteroidsView :: Signal [Just AsteroidModel] [Picture]

asteroidsView would have to do the following:
* route the input list to a list of "asteroidView" signals.
* When there is a "Nothing" in the input list, the corresponding (now 
exploding) view is moved to a list of "zombie asteroids" where it 
remains until its explosion animation is over.
* When the input list is longer than the list of current astroidView 
signals, the list is extended.

This would avoid the need for bookkeeping ids.

Regards,
Nathan



More information about the Haskell-Cafe mailing list