Well, I've defined my own datatype that represent one-variable polynoms in Haskell.
data Polinomio a where
Pol :: (Num a) => a -> Integer -> Polinomio a -> Polinomio a
Cons :: (Num a) => a -> Polinomio a
I used here GADTs to constraint the a variable to belong to Num Class. Now I want to define my own instance for the Functor Class
instance Functor Polinomio where
fmap f (Cons x) = Cons $ f x
fmap f (Pol x g p) = Pol (f x) g (fmap f p)
And It does'nt compile giving me this reason:
Polinomio_GADT.hs:31:23:
Could not deduce (Num b) arising from a use of `Cons'
from the context (Num a)
bound by a pattern with constructor
Cons :: forall a. Num a => a -> Polinomio a,
in an equation for `fmap'
at Polinomio_GADT.hs:31:13-18
Possible fix:
add (Num b) to the context of
the data constructor `Cons'
or the type signature for
fmap :: (a -> b) -> Polinomio a -> Polinomio b
In the expression: Cons
In the expression: Cons $ f x
In an equation for `fmap': fmap f (Cons x) = Cons $ f x
Polinomio_GADT.hs:32:26:
Could not deduce (Num b) arising from a use of `Pol'
from the context (Num a)
bound by a pattern with constructor
Pol :: forall a.
Num a =>
a -> Integer -> Polinomio a -> Polinomio a,
in an equation for `fmap'
at Polinomio_GADT.hs:32:13-21
Possible fix:
add (Num b) to the context of
the data constructor `Pol'
or the type signature for
fmap :: (a -> b) -> Polinomio a -> Polinomio b
In the expression: Pol (f x) g (fmap f p)
In an equation for `fmap':
fmap f (Pol x g p) = Pol (f x) g (fmap f p)
In the instance declaration for `Functor Polinomio'
So I try to add this constraint to the fmap definition using language extension InstanceSigs:
instance Functor Polinomio where
fmap :: (Num a,Num b) -> (a -> b) -> Polinomio a -> Polinomio b
fmap f (Cons x) = Cons $ f x
fmap f (Pol x g p) = Pol (f x) g (fmap f p)
And It not works getting this from the compiler:
Polinomio_GADT.hs:31:13:
Predicate `(Num a, Num b)' used as a type
In the type signature for `fmap':
fmap :: (Num a, Num b) -> (a -> b) -> Polinomio a -> Polinomio b
In the instance declaration for `Functor Polinomio'
Any idea how to fix that?
Functor
class. There's anRFunctor
class in thermonad
package that allows constraining the types, but you can't makePolinomio
aFunctor
. – Daniel Fischer