简体   繁体   中英

Haskell Unable to create instance of a TypeClass

I am new to Haskell and was trying to create a class with an instance.

I have the following code and I am trying to say that: 1) Branch can hold any type in its first position, 2) Make a class Linear which takes the linear thing and returns a number 3) Make Branch an instance of Linear if the first thing the Branch holds is something that is part of the Num class.

data Branch a = Branch a Integer deriving (Show, Eq)

class Linear l where
    length :: (Num a) => l -> a

instance (Num a) => Linear (Branch a) where
    length (Branch len _) = len

I get the error: Could not deduce (a ~ a1) from the context (Num a) bound by the instance declaration at.....

Does anybody know how to express in Haskell what it is I'm trying to say?

Your class definition says that length must be able to return any Num type that the user requests. So if the user wants an Integer, the length method must give him an Integer. And if he wants an Int or a Double instead, length must give him that too.

However the length function you supply in your instance declaration does not meet the requirement. For example when you call length on a Branch Integer , length will return an Integer . It won't return an Int or a Double even if the user asks for it.

One way to make your code work would be to use multi-parameter type classes to define Linear with two parameters where the second type is the numeric type length should return. You could then have an instance for Linear (Branch a) a . You may also want to use the Functional Dependencies extension to make this more usable. Instead of a second type parameter, you may also use the Type Families extension to achieve a similar effect.

Another way would be to change the instance declaration to require Integral a instead of Num a and then use fromIntegral len as the return value. This will convert the integral type stored in the Branch to whichever numeric type the User requested. The caveat is, of course, that you branches with non-integral numeric values, won't be instances of Linear this way.

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