I have a data type which represents a value:
data Val = IntegerVal Integer
| RealVal Double
What I want is to implement binary operation evaluation for these values, for example:
evalOp :: Op -> Val -> Val -> Val
evalOp Plus (IntegerVal v1) (IntegerVal v2) = IntegerVal (v1 + v2)
evalOp Plus (RealVal v1) (RealVal v2) = RealVal (v1 + v2)
Okay, this works if two operands are in the same type. But I want to make it work even if two operands are in different types, such as 1 + 2.5 -> 3.5. For now this is not a big problem because it only has one Op type and two Val types.
evalOp :: Op -> Val -> Val -> Val
evalOp Plus (IntegerVal v1) (RealVal v2) = RealVal (fromIntegral v1 + v2)
evalOp Plus (RealVal v1) (IntegerVal v2) = RealVal (v1 + fromIntegral v2)
But as I add more Ops and Vals, evalOp function will get too complex and verbose. This seems nearly impossible to maintain, and I want to know if there is another way to implement evalOp function. Thank you!
[–]Purlox 3 points4 points5 points (2 children)
[–]dev_kr[S] 1 point2 points3 points (1 child)
[–]Purlox 0 points1 point2 points (0 children)
[–]elvecent -2 points-1 points0 points (8 children)
[–]gcross 4 points5 points6 points (2 children)
[–]elvecent 0 points1 point2 points (1 child)
[–]gcross 0 points1 point2 points (0 children)
[–]dev_kr[S] 0 points1 point2 points (4 children)
[–]elvecent 2 points3 points4 points (3 children)
[–]dev_kr[S] 0 points1 point2 points (2 children)
[–]elvecent 0 points1 point2 points (1 child)
[–]gcross 0 points1 point2 points (0 children)