Forcing type conversion - probably FAQ(?)

Hello, I'm trying to make work the following code (I'm using GHCi with flags -fglasgow-exts -fallow-undecidable-instances): infixl 6 :+, :- infixl 6 .+, .- data TMyExpr = TMyExpr :+ TMyExpr | TMyExpr :- TMyExpr | Val Int | Id String class MkExpr a b where (.+) :: a -> b -> TMyExpr (.-) :: a -> b -> TMyExpr instance MkExpr Int Int where (.+) a b = (Val a) :+ (Val b) (.-) a b = (Val a) :- (Val b) instance MkExpr Int TMyExpr where (.+) a b = (Val a) :+ b (.-) a b = (Val a) :- b instance MkExpr TMyExpr Int where (.+) a b = a :+ (Val b) (.-) a b = a :- (Val b) instance MkExpr TMyExpr TMyExpr where (.+) a b = a :+ b (.-) a b = a :- b It compiles fine, no problem. Nevertheless, writing (3::Int) .+ (4::Int) seems to me quite clumsy, but 3 .+ 4 does not work. :-( It says the 3 is from class Num and no variant is present for it, I know, it is not present, but how to force it to convert it to Int "automatically"? When I try to incorporate instance (Num a, Num b) => MkExpr a b where (.+) a b = (Val . round a) :+ (Val . round b) (.-) a b = (Val . round a) :- (Val . round b) the situation is even worse. :-( I tried several modifications, but they don't work either. :-\ I was trying to find the discussion (I wonder whether it went on the similar topic through the list recently), but failed. :-( If someone can just point me to any resource I could study the possible solutions - maybe I put wrong data to google. ;-) Or just to stop me, if I'm trying to do impossible... :-\ Thx, Dusan

On Wed, 1 Dec 2004, Dusan Kolar wrote:
Hello,
I'm trying to make work the following code (I'm using GHCi with flags -fglasgow-exts -fallow-undecidable-instances):
infixl 6 :+, :- infixl 6 .+, .-
data TMyExpr = TMyExpr :+ TMyExpr | TMyExpr :- TMyExpr | Val Int | Id String
What about introducing a single type parameter class which can convert both Int and TMyExpr to TMyExpr? (untested code follows) class MkExpr a where toExpr :: a -> TMyExpr (.+) :: (MkExpr a, MkExpr b) => a -> b -> TMyExpr (.+) x y = toExpr x :+ toExpr y
participants (2)
-
Dusan Kolar
-
Henning Thielemann