Haskell: "Non type-variable argument in the constraint: Eq Bit" and "No instance for (Eq Bit) arising drom a use of '=='" - haskell

data Bit = One
| Zero
deriving Show
type Bits = [Bit]
bits2String :: Bits -> String
bits2String [] = ""
bits2String (x:xs) | x == One = "1" ++ bits2String xs
| x == Zero = "0" ++ bits2String xs
This Code causes following error message:
No instance for (Eq Bit) arising drom a use of '=='
For this error you can find a lot of solutions on SO. They always say you need to add Eq like that:
bits2String :: (Eq Bit) => Bits -> String
bits2String [] = ""
bits2String (x:xs) | x == One = "1" ++ bits2String xs
| x == Zero = "0" ++ bits2String xs
But this doesnt work for me and causes following error
Non type-variable argument in the constraint: Eq Bit
(Use FlexibleContexts to permit this)
{-# LANGUAGE FlexibleContexts #-} doesnt work either.

The original error message is the key one:
No instance for (Eq Bit) arising drom a use of '=='
This arises because you are using the == operator, which is only available for instances of the Eq typeclass - and you haven't given such an instance.
That's easily fixed though. For one you can easily provide the instance manually:
instance Eq Bit where
One == One = True
Zero == Zero = True
_ == _ = False
I wouldn't recommend that you do that though. You can ask Haskell to generate that exact instance for you by simply adding a deriving clause to the type definition. In fact you're already using one, so you can just add Eq to the list of instances you want to derive:
data Bit = One
| Zero
deriving (Show, Eq)
Adding this instance is a good idea in general, because you might well need to compare Bits for equality at some point, especially when working with lists of them - many list functions such as elem depend on Eq instances for their members.
But you can rewrite your bits2String function to not need an Eq instance at all, by pattern matching on the two data constructors:
bits2String :: Bits -> String
bits2String [] = ""
bits2String (One:xs) = "1" ++ bits2String xs
bits2String (Zero:xs) = "0" ++ bits2String xs
In fact, you've basically reimplemented the map function here, so what I would likely do is to define:
bitToChar :: Bit -> Char
bitToChar Zero = '0'
bitToChar One = '1'
(especially as it's the kind of general utility function that you may well want for other things)
and then
bits2String = map bitToChar
None of those require an Eq instance - but it's likely a good idea to derive it anyway, for the reasons I mentioned.

You make use of x == Zero, so of the (==) :: Eq a => a -> a -> Bool function, but you did not make Bit an instance of Eq. You can do so by adding it to the deriving clause, such that Haskell can automatically implement an instance of Eq for your Bit data type:
data Bit = One
| Zero
deriving (Eq, Show)
By default two items are the same if the data constructor is the same, and the parameters (but here your data constructors have no parameters, so it will only check equality of the data constructors).
That being said, you do not need these to be an instance of Eq, you can use pattern matching instead. Indeed:
bits2String :: Bits -> String
bits2String = map f
where f Zero = '0'
f One = '1'
Here we make use of map :: (a -> b) -> [a] -> [b] to convert a list of items to another list by applying a function to each of the items in the original list. Since Bits is a list of Bits, and String is a list of Chars, we can thus map each Bit to a Char to obtain a String of '0's and '1's for the Zero and Ones respectively.

Related

Understanding Haskell Type Class use in Type Declarations

When we have a function that compares two things using the == comparison operator we add something like Eq a => a... to the type declaration; but this doesn't always seem to be the case.
For example, given the following function:
tail' xs = if length xs == 0
then []
else drop 1 xs
We make use of the == comparison operator, so I assumed the correct type decalaration would be:
tail':: (Eq a) => [a] -> [a]
However, running :t tail' tells me that the correct type decalartion is:
tail':: [a] -> [a]
Why is this the case? Why isn't Eq required in the type declaration?
Eq a => t says that a must be an instance of Eq in the type t. A type being an instance of Eq means that == is defined for that type. But in your definition of tail', you never use == on an a, not even by proxy. The actual use of == is in length xs == 0. The type of length xs (and 0) is Int, and Int is already an instance of Eq, so we already know it has == defined. Since you never use == on an a, you don't need an Eq a constraint.
If, however, you had said xs == [], which seems equivalent (both test whether a list is empty), you would have incurred an Eq a constraint. This is because == on [a] requires an Eq a constraint since it uses == on each list's entries to compare the lists. Since you can use length xs == 0 (or, even better, null xs), though, this added constraint is spurious and should be avoided.
(As an aside, drop 1 [] = [] so you don't even need your if, but that isn't relevant to the question asked.)

Eq definition for alternative version numbering approach

I am trying to define Eq operator for alternative version numbering approach.
type VersionCompound = Maybe Int -- x, 0, 1, 2, ...
type VersionNumber = [VersionCompound] -- x.x, x.0, x.1, x.2, ... , 1.0, 1.1, 1.2, ... 1.x.x, 2.x.x, 3.x.x, ...
instance Eq VersionNumber where
[] == [] = True
(x:[]) == (y:[]) = x == y
(Nothing:xs) == ys = (xs == ys)
xs == (Nothing:ys) = (xs == ys)
It is expected that it returns True for following cases: x.x.x == x, 1.x.x == x.1.x.x, x.1 == 1, etc. But instead it returns an error:
VersionNumber.hs:58:34:
Overlapping instances for Eq [VersionCompound]
arising from a use of ‘==’
Matching instances:
instance Eq a => Eq [a] -- Defined in ‘GHC.Classes’
instance Eq VersionNumber -- Defined at VersionNumber.hs:55:10
In the expression: (xs == ys)
In an equation for ‘==’: (Nothing : xs) == ys = (xs == ys)
In the instance declaration for ‘Eq VersionNumber’
Any ideas how to fix it?
EDIT: My approach to this problem via pattern matching on lists turned out to be incomplete. I wanted to disregard any arbitrary list of x's (or Nothings) on the left hand side of the given version. So, for example, x.x.x.x.x would be equal to x.x.x and to x. Similarly, x.x.x.1 would be equal to x.x.1 and to 1. If there's an x in the middle, it won't be thrown away. So, for this case, x.x.1.x.0 would be equal to x.1.x.0 and 1.x.0. Yet another example: x.1.x.x.0.x is equal to 1.x.x.0.x and x.1.x.0.x is equal to 1.x.0.x (You just remove x's on the left side).
What I was struggling with after fixing an error Overlapping instances for Eq [VersionCompound] is how to get x.x.x == x -> True with pattern matching. But, as #WillemVanOnsem brilliantly noted, it should be achieved not via pattern matching, but with function composition.
PS. I personally encourage you to upvote the answer by #WillemVanOnsem because his solution is really elegant, required some effort to come up with and represents the essence of Haskell power.
You use type aliases. This means that you have not defined a separate type VersionNumber or VersionCompound; you simply have constructed an alias. Behind the curtains, Haskell sees VersionNumber as simply [Maybe Int].
Now if we look at Haskell's library, we see that:
instance Eq Int where
-- ...
instance Eq a => Eq (Maybe a) where
-- ...
instance Eq a => Eq [a] where
-- ...
So that means that Eq Int is defined, that Eq (Maybe Int) is defined as well, and thus that Eq [Maybe Int] is defined by the Haskell library as well. So you actually have already constructed an Eq VersionNumber without writing one. Now you try to write an additional one and, of course, the compiler gets confused with which one to pick.
There are ways to resolve overlapping instances, but this will probably only generate more trouble.
Thus, you better construct a data type with a single constructor. For example:
type VersionCompound = Maybe Int
data VersionNumber = VersionNumber [VersionCompound]
Now, since there is only one constructor, you better use a newtype:
type VersionCompound = Maybe Int
newtype VersionNumber = VersionNumber [VersionCompound]
and now we can define our special instance like:
instance Eq VersionNumber where
(VersionNumber a) == (VersionNumber b) = a =*= b
where [] =*= [] = True
(x:[]) =*= (y:[]) = x == y
(Nothing:xs) =*= ys = (xs =*= ys)
xs =*= (Nothing:ys) = (xs =*= ys)
So we thus unwrap the constructors and then use another locally defined function =*= that works like you defined it in your question.
Mind however that you forgot a few patterns in your program, like for instance Just x : xs on both the left and the right side. So, you better fix these first. If I run your code through a compiler, I get the following warnings:
Pattern match(es) are non-exhaustive
In an equation for ‘=*=’:
Patterns not matched:
[] (Just _:_)
[Just _] []
[Just _] (Just _:_:_)
(Just _:_:_) []
How you want to handle these cases is of course up to you. #DanielWagner suggests to use:
import Data.Function(on)
import Data.Maybe(catMaybes)
instance Eq VersionNumber where
(VersionNumber a) == (VersionNumber b) = on (==) catMaybes a b
This will filter out the Nothing values of both VersionNumbers and then check whether the values in the Just generate the same list. So 3.x.2.x.x.1 will be equal to 3.2.1 and x.x.x.x.x.3.2.1.
EDIT: based on your specification in comment, you are probably looking for:
import Data.Function(on)
instance Eq VersionNumber where
(VersionNumber a) == (VersionNumber b) = on (==) (dropWhile (Nothing ==)) a b

Creating Instance of Eq for custom data type in Haskell

I have made some custom Data types for number representation in Haskell, now I want to implement Eq instances for it, but I am somehow stuck. So I have already made:
data Digit = Zero | One | Two
type Digits = [Digit]
data Sign = Pos | Neg -- Pos fuer Positive, Neg fuer Negative
newtype Numeral = Num (Sign,Digits)
instance Eq Sign where
(==) Pos Pos = True
(==) Neg Neg = True
(==) _ _ = False
instance Eq Digit where
(==) Zero Zero = True
(==) One One = True
(==) Two Two = True
(==) _ _ = False
Now I want to check out the Sign in my custom type Numeral so I tried this:
instance (Eq Sign) => Eq (Numeral) where
(==) Num(x,_)== Num(y,_) = x==y
But I get this error: Parse error in pattern : (==)
Mostly putting what I've already written in the comments in a more fleshed out form:
There are a few problems with your code:
You have to indent the code under the instance declarations. That way you tell the compiler what code belongs to the instance declaration.
In the following line you are asking for a type class constraint on a concrete type (Eq Sign =>). This is not possible in standard Haskell and even if you were to follow the compiler instructions and enable the FlexibleInstances language extension it wouldn't make sense.
instance (Eq Sign) => Eq (Numeral) where
Type class constraints are only used for type variables. For example:
double :: Num a => a -> a
double x = x + x
Here we say, that the function double only works for all types that implement Num. double :: Num Int => Int -> Int on the other hand is redundant, because we already know, that Int has a Num instance. The same for Eq Sign.
For instances such constraints only make sense, if the type you are writing an instance for contains another polymorphic type. Fox example instance Ord a => Ord [a]. Here we would use the Ord instance of the elements of the list to lexiographically order lists.
You can define (==) either in infix or prefix form, but not both. So either (==) (Num (x,_)) (Num (y,_)) = x == y or Num (x,_) == Num (y,_) = x == y.
Newtyping tuples to create a product type is rather strange. Newtypes are usually used if you want to use the functionality that is already present for the more complex underlying type. However here that is not the case, you just want a normal product of Digits and Sign.
You are only comparing the Sign of the numbers. While technically a valid Eq instance, I think you also want to compare the digits of the number probably truncating leading zeros. In the code below I didn't truncate zeros though, to keep it simple.
data Digit = Zero | One | Two
type Digits = [Digit]
data Sign = Pos | Neg
data Numeral = Num Sign Digits
instance Eq Sign where
(==) Pos Pos = True
(==) Neg Neg = True
(==) _ _ = False
instance Eq Digit where
(==) Zero Zero = True
(==) One One = True
(==) Two Two = True
(==) _ _ = False
instance Eq Numeral where
Num s1 x1 == Num s2 x2 = s1 == s2 && x1 == x2

Haskell Ord instance paradox on Eq

I want to be able to order Polynomes with comparing first by lenght (degree), second by coefficient. Polynomes are list of doubles with [1,2,3] = 3x²+2x+1 .
But if there is a zero as last element it should be dropped, so I wrote a function doing that called realPolynom. realPolynom [1,2,3,0] = [1,2,3]
Now, my Ord instance looks like:
instance Ord Polynom where
compare a b = compare ((realLength a), reverse (pol2list (realPolynom a))) ((realLength b), reverse (pol2list (realPolynom b)))
realLength is just Length of polynom without zeros as last.
pLength :: Polynom -> Int
pLength (Polynom(a)) = length a
realLength :: Polynom -> Int
realLength a = pLength(realPolynom(a))
pol2list is Polynom p = p
pol2list :: Polynom -> [Double]
pol2list (Polynom p) = p
Problem is:
[0,2,0] < [0,2,3] true, which is good
[0,2,0] < [0,2] false, also good
[0,2,0] > [0,2] false, also good
[0,2,0] == [0,2] false, which is not good! should be equal!
Instead of deriving Eq, you should probably write
instance Eq Polynom where
a == b = compare a b == EQ
The best solution might be to ensure that no leading zeroes ever turn up in the first place. I.e. instead of ever building polynomes manually from lists, you feed them to a "smart constructor" that eats away zeroes before packing the Polynome data type.
May seem a bit of a OO-ish thing to do, but sometimes this kind of encapsulation is just the way to go, even in functional languages.
Something like this should work:
instance Eq Polynom where
x == y = pol2list (realPolynom x) == pol2list (realPolynom y)
Unfortunately, in this case the derived Eq instance is not the intended one.

Get a list of the instances in a type class in Haskell

Is there a way to programmatically get a list of instances of a type class?
It strikes me that the compiler must know this information in order to type check and compile the code, so is there some way to tell the compiler: hey, you know those instances of that class, please put a list of them right here (as strings or whatever some representation of them).
You can generate the instances in scope for a given type class using Template Haskell.
import Language.Haskell.TH
-- get a list of instances
getInstances :: Name -> Q [ClassInstance]
getInstances typ = do
ClassI _ instances <- reify typ
return instances
-- convert the list of instances into an Exp so they can be displayed in GHCi
showInstances :: Name -> Q Exp
showInstances typ = do
ins <- getInstances typ
return . LitE . stringL $ show ins
Running this in GHCi:
*Main> $(showInstances ''Num)
"[ClassInstance {ci_dfun = GHC.Num.$fNumInteger, ci_tvs = [], ci_cxt = [], ci_cls = GHC.Num.Num, ci_tys = [ConT GHC.Integer.Type.Integer]},ClassInstance {ci_dfun = GHC.Num.$fNumInt, ci_tvs = [], ci_cxt = [], ci_cls = GHC.Num.Num, ci_tys = [ConT GHC.Types.Int]},ClassInstance {ci_dfun = GHC.Float.$fNumFloat, ci_tvs = [], ci_cxt = [], ci_cls = GHC.Num.Num, ci_tys = [ConT GHC.Types.Float]},ClassInstance {ci_dfun = GHC.Float.$fNumDouble, ci_tvs = [], ci_cxt = [], ci_cls = GHC.Num.Num, ci_tys = [ConT GHC.Types.Double]}]"
Another useful technique is showing all instances in scope for a given type class using GHCi.
Prelude> :info Num
class (Eq a, Show a) => Num a where
(+) :: a -> a -> a
(*) :: a -> a -> a
(-) :: a -> a -> a
negate :: a -> a
abs :: a -> a
signum :: a -> a
fromInteger :: Integer -> a
-- Defined in GHC.Num
instance Num Integer -- Defined in GHC.Num
instance Num Int -- Defined in GHC.Num
instance Num Float -- Defined in GHC.Float
instance Num Double -- Defined in GHC.Float
Edit: The important thing to know is that the compiler is only aware of type classes in scope in any given module (or at the ghci prompt, etc.). So if you call the showInstances TH function with no imports, you'll only get instances from the Prelude. If you have other modules in scope, e.g. Data.Word, then you'll see all those instances too.
See the template haskell documentation: http://hackage.haskell.org/packages/archive/template-haskell/2.5.0.0/doc/html/Language-Haskell-TH.html
Using reify, you can get an Info record, which for a class includes its list of instances. You can also use isClassInstance and classInstances directly.
This is going to run into a lot of problems as soon as you get instance declarations like
instance Eq a => Eq [a] where
[] == [] = True
(x:xs) == (y:ys) = x == y && xs == ys
_ == _ = False
and
instance (Eq a,Eq b) => Eq (a,b) where
(a1,b1) == (a2,b2) = a1 == a2 && b1 == b2
along with a single concrete instance (e.g. instance Eq Bool).
You'll get an infinite list of instances for Eq - Bool,[Bool],[[Bool]],[[[Bool]]] and so on, (Bool,Bool), ((Bool,Bool),Bool), (((Bool,Bool),Bool),Bool) etcetera, along with various combinations of these such as ([((Bool,[Bool]),Bool)],Bool) and so forth. It's not clear how to represent these in a String; even a list of TypeRep would require some pretty smart enumeration.
The compiler can (try to) deduce whether a type is an instance of Eq for any given type, but it doesn't read in all the instance declarations in scope and then just starts deducing all possible instances, since that will never finish!
The important question is of course, what do you need this for?
I guess, it's not possible. I explain you the implementation of typeclasses (for GHC), from it, you can see, that the compiler has no need to know which types are instance of a typeclass. It only has to know, whether a specific type is instance or not.
A typeclass will be translated into a datatype. As an example, let's take Eq:
class Eq a where
(==),(/=) :: a -> a -> Bool
The typeclass will be translated into a kind of dictionary, containing all its functions:
data Eq a = Eq {
(==) :: a -> a -> Bool,
(/=) :: a -> a -> Bool
}
Each typeclass constraint is then translated into an extra argument containing the dictionary:
elem :: Eq a => a -> [a] -> Bool
elem _ [] = False
elem a (x:xs) | x == a = True
| otherwise = elem a xs
becomes:
elem :: Eq a -> a -> [a] -> Bool
elem _ _ [] = False
elem eq a (x:xs) | (==) eq x a = True
| otherwise = elem eq a xs
The important thing is, that the dictionary will be passed at runtime. Imagine, your project contains many modules. GHC doesn't have to check all the modules for instances, it just has to look up, whether an instance is defined anywhere.
But if you have the source available, I guess an old-style grep for the instances would be sufficient.
It is not possible to automatically do this for existing classes. For your own class and instances thereof you could do it. You would need to declare everything via Template Haskell (or perhaps the quasi-quoting) and it would automatically generate some strange data structure that encodes the declared instances. Defining the strange data structure and making Template Haskell do this are details left to whomever has a use case for them.
Perhaps you could add some Template Haskell or other magic to your build to include all the source files as text available at run-time (c.f. program quine). Then your program would 'grep itself'...

Resources