I was trying to define a very simple data structure that is suppose to add an Infinity
element to any type under Num
. I also put it under a defined class NumContainer
, which has a method fromNum
that construct a NumWithInf
using a regular Num
. The code is really straight forward.
data NumWithInf a = Infinity | Finite a deriving Show
class NumContainer k where
fromNum :: Num a => a -> k
instance Num a => NumContainer (NumWithInf a) where
fromNum x = Finite x
However when I ran it, GHCI gave me the following error:
hw.hs:7:24:
Could not deduce (a ~ a1)
from the context (Num a)
bound by the instance declaration at hw.hs:6:10-45
or from (Num a1)
bound by the type signature for
fromNum :: Num a1 => a1 -> NumWithInf a
at hw.hs:7:5-24
`a' is a rigid type variable bound by
the instance declaration at hw.hs:6:10
`a1' is a rigid type variable bound by
the type signature for fromNum :: Num a1 => a1 -> NumWithInf a
at hw.hs:7:5
In the first argument of `Finite', namely `x'
In the expression: Finite x
In an equation for `fromNum': fromNum x = Finite x
Failed, modules loaded: none.
I understand that it says the x
in Finite x
doesn't necessarily have the same type as a
in the signature fromNum :: Num a => a -> k
. How should I specify this?