barakcaf
barakcaf

Reputation: 1324

Creating an instance for a typeclass throws :"Couldn't match expected type ‘f’ with actual type"

I am new to Haskell and i'm trying to learn how to use classe,

I have the class:

class SomeClass f where
doSome :: Integer -> f

the data type:

 data SomeData = D1 Integer 
                | D2 SomeData SomeData 

and I'm trying to create the instance:

instance SomeClass SomeData where
doSome x = D1 x

but the ghci gives me the error:

Couldn't match expected type ‘f’ with actual type ‘SomeClass’

I've seen some question regarding this issue, but i couldn't make them work for me.

how can i fix this?

Upvotes: 0

Views: 96

Answers (1)

ErikR
ErikR

Reputation: 52039

The use of D1 after D2 is not valid here:

data SomeData = D1 Integer 
                | D2 D1 D1
                     ^^^^^

Where D1 occurs after D2 you need a type, but D1 is a function.

You probably meant to write:

data SomeData = D1 Integer 
                | D2 SomeData SomeData

With this change your code compiles. (I also change the name do to another name which is not a Haskell keyword):

data SomeData = D1 Integer | D2 SomeData SomeData

class SomeClass f where
  foo :: Integer -> f

instance SomeClass SomeData where
  foo x = D1 x

Upvotes: 4

Related Questions