[Haskell-beginners] different function implementations for different values of typevar - is it possible?

Sergey Mironov ierton at gmail.com
Sat Jan 23 16:17:20 EST 2010

Hi all.
I am writing a Monad intace for my own Writer-like data type
"HtmlWriter" (see code below).
The main HtmlWriter's difference is in return() function. I'd like it
to convert user data (a) to html.
But here come troubles. In general, there are two cases:
1) (HTML a) exists
2) (HTML a) doesn't exist

So, i need to write different implementations of return() for both
cases. Something like this:
1)     return a = HtmlWriter (a, toHtml a)
2)     return a = HtmlWriter (a, toHtml (show a))
I can't find a way to do it. Is it possible somehow? Please, help.

Here is the code:

import Control.Monad
import Text.XHtml.Transitional

newtype HtmlWriter a = HtmlWriter { runHtmlWriter :: (a, Html) }

instance Monad (HtmlWriter) where
    return a = HtmlWriter (a, toHtml a)
    -- ??? return a = HtmlWriter (a, toHtml (show a))
    m >>= k  = HtmlWriter $ let
        (a, w)  = runHtmlWriter m
        (b, w') = runHtmlWriter (k a)
        in (b, w `mappend` w')

Thanks, Sergey.

More information about the Beginners mailing list