[Haskell-beginners] Modifications inside a Reader?

Brent Yorgey byorgey at seas.upenn.edu
Thu Jun 18 14:25:53 EDT 2009


On Wed, Jun 17, 2009 at 08:32:53PM -0700, Brian Troutwine wrote:
> Hello all.
> 
> I'm writing a UDP echo server, full source given below. The current
> implementation echoes back the "payload" of every incoming message but
> I would prefer that only unique payloads be echoed back. To that end
> I've started in with Data.BloomFilter but am not sure how to update it
> accordingly. I imagine that Reader is probably the wrong monad to be
> using though I'm unsure how I might modify my program to use State.
> Could someone lead me along a bit?
> 
> Also, any general comments on the style of my program?

Looks nice.  Changing your program to use 'State' instead of 'Reader'
(which is indeed the wrong monad if you want to update) should be a
piece of cake!

> type Echo = StateT Globals IO

Now you should use 'gets' instead of 'asks':

> run :: Echo ()
> run = forever $ do
>   s <- gets socketG
>   ...

Then you'll probably want a little utility function for updating the
Bloom filter, like this:

> modifyBloom :: (Bloom Bytestring -> Bloom Bytestring) -> Echo ()
> modifyBloom f = modify (\s -> s { bloomF = f (bloomF s) })

('modify' is another State method; the ugliness and repetition in
evidence above is because of the unwieldy record-update syntax, which
is exactly why you want a helper function =).

Now you can use 'modifyBloom f' as an Echo () action which applies the
transformation f to the current Bloom filter.  And that's all!

-Brent


More information about the Beginners mailing list