简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM