[Haskell-cafe] Class

Slavomir Kaslev slavomir.kaslev at gmail.com
Thu Nov 2 08:42:21 EST 2006


On 11/2/06, Sebastian Sylvan <sylvan at student.chalmers.se> wrote:
> On 11/2/06, Slavomir Kaslev <slavomir.kaslev at gmail.com> wrote:
>
> >
> > Visible 'subclasses' Show. Doesn't this mean that Visible should be
> > defined for all types with Show instances?
>
> No, it just means that any type that you want to instantiate in
> Visible needs to also have a Show instance (is this a restriction you
> really want? See below).

Well, yes that's what I meant. I want class Visible for objects that
have Show instance and I want to be able to use this Show instance in
the definition of Visible.

Again this is not some practical example, I am just trying to grasp
Haskell classes and instances.

>
> You could do something like
>
> instance Show a => Visible a
>
> (the default implementations that you provided in the class should be
> enough, you could possibly move the implementations to the "Show
> instance" and remove the Show super class from the Visible class -
> then you could make even non-Show types instances of Visible without
> having to define their instance for Show as well).
>
> /S
>
>
> --
> Sebastian Sylvan
> +46(0)736-818655
> UIN: 44640862
>

This doesn't work either:

import List

class Visible a where
   toString :: a -> String
   size :: a -> Int

instance Show a => Visible a where
    toString = show
    size = length . show

instance Visible a => Visible [a] where
   toString = concat . map toString
   size = foldl (+) 0 . map size

vSort :: (Visible a, Ord a) => [a] -> String
vSort = toString . List.sort

s = vSort [1..3]

gives:

    Illegal instance declaration for `Visible a'
	(The instance type must be of form (T a b c)
	 where T is not a synonym, and a,b,c are distinct type variables)
    In the instance declaration for `Visible a'
Failed, modules loaded: none.

at instance Show a => Visible a where.

Probably I should reconsider my expectations? How should something
like this designed?

-- 
Slavomir Kaslev


More information about the Haskell-Cafe mailing list