[Haskell-cafe] type/class question: toString

Nicholas Messenger nmessenger at gmail.com
Wed Nov 7 16:34:01 EST 2007


If you're willing to have an extra Typeable constraint, this does what you want:

> import Data.Typeable (Typeable, cast)
> import Data.Maybe (fromMaybe)
>
> toString :: (Show a, Typeable a) => a -> String
> toString x = fromMaybe (show x) (cast x)

*Main> toString "blah"
"blah"
*Main> toString 1
"1"
*Main> toString (Just 0.5)
"Just 0.5"

So Strings are just cast into the result.  Non-strings become Nothing,
which fromMaybe turns into (show x).

--
Nicholas Messenger
nmessenger at gmail.com


On Nov 6, 2007 4:23 PM, Graham Fawcett <graham.fawcett at gmail.com> wrote:
> On Nov 6, 2007 3:29 PM, Graham Fawcett <graham.fawcett at gmail.com> wrote:
> > On Nov 6, 2007 2:21 PM, Jeff Polakow <jeff.polakow at db.com> wrote:
> > >   Have you tried using -fglasgow-exts? That should enable all ghc
> > > extensions.
>
> If anyone's interested, I had best results when I added the flag
> -fallow-incoherent-instances. Without it, I could not handle numbers
> without declaring their types, e.g. 'toString (33 :: Int)' would work,
> but 'toString 33' would lead to:
>
>     Ambiguous type variable `t' in the constraints:
>       `ToString t'
>         arising from use of `toString'
>         at /home/graham/tmp/ToString.hs:13:15-25
>       `Num t'
>         arising from the literal `33'
>         at /home/graham/tmp/ToString.hs:13:24-25
>     Probable fix: add a type signature that fixes these type variable(s)
>
> Here's the code I ended up with.
>
> {-# OPTIONS -fglasgow-exts -fallow-overlapping-instances #-}
> {-# OPTIONS -fallow-incoherent-instances -fallow-undecidable-instances #-}
>
> module ToString (ToString(..)) where
>
> class Show a => ToString a      where toString :: a -> String
> instance ToString String        where toString s = s
> instance (Show a) => ToString a where toString s = show s
>
>
> Thanks to all who responded; I learned a lot from this.
>
> Graham
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>


More information about the Haskell-Cafe mailing list