[Haskell-cafe] Class/Instance : what am I doing wrong in this example ?

david48 dav.vire+haskell at gmail.com
Thu Dec 20 11:44:25 EST 2007

On Dec 20, 2007 5:26 PM, Tillmann Rendel
<rendel at rbg.informatik.tu-darmstadt.de> wrote:

> at this point fInit has this type:
>    FString -> a -> FString
> >   fInit (FString n _) s = FString n (take n s)
> but your implementation has this type
>    FString -> String -> FString
> These types are incompatible, your fInit implementation should be able
> to work with whatever type a the caller has choosen to provide. Maybe

That was a very clear explanation of what's wrong, thanks a lot !

> you should try one of

>    class Gadget g where
>      fInit  :: g -> String -> g

This will not do, I want instances of gadget that work with other
values than string.

> or
>    class Gadget g a where
>      fInit  :: g -> a -> g

A bit of explanation.

I want types of class "Gadget" to be able to hold values of some type.
for example, some of the types in the class Gadget would hold strings,
some would hold Integers.
With a variable of a type belonging to the class Gadget, I want to be able to
- Initialise it
- Fetch the value it holds
- Have the user input the value
- Display the value

To keep it simple, in this example I only kept the funtion to initialise.

So it seems I have to use the multiparameter class version, but I'm
stuck here as well :

class Gadget g a where
  fInit  :: g -> a -> g

data FString = FString !Int !String deriving Show

instance Gadget FString String where
  fInit (FString n _) s = FString n (take n s)

fString :: Int -> FString
fString n = FString n ""


*Main> :r
[1 of 1] Compiling Main             ( Gadget.hs, interpreted )
Ok, modules loaded: Main.
*Main> fString 5 ""

    Couldn't match expected type `[Char] -> t'
     against inferred type `FString'
    In the expression: fString 5 ""
    In the definition of `it': it = fString 5 ""

More information about the Haskell-Cafe mailing list