0
votes

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?

1
The indentation is wrong, and I really doubt your method is named do. Can you provide your actual code?Reid Barton
@ Red Barton Tnx! - you're right, my indentation was wrong (the names also, I edited my question to reflect that but that's not the important part). after fixing it, it compiled and run as expected (arrr the errors code wasn't useful at all)barakcaf
@ Red Barton this will teach me to indent after a 'where' clausebarakcaf
OK, great. I must admit it never occurred to me that it's syntactically valid to put an instance declaration between a function's type signature and its definition.Reid Barton
Don't update the question with the fix... now it looks like you asked "I have [perfectly working code here], why doesn't it work?"user253751

1 Answers

4
votes

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