Reputation: 657
The code bellow works pretty well for input like this:
*Main> eval 'y' (21 :: Int)
42
*Main> eval 'x' 'a'
42
*Main> eval (21 :: Int) (21 :: Int)
42
*Main> eval (42 :: Int) 'a'
42
The general problem behind this is that I want to add two things. Adding to Int
s is not hard to realize (it's already built in). But I've a given function (here geti
) which resolves Char
s to Int
s and my add
-function now should add two Int
s as well as Int
combined with Char
(in every permutation). The Char
s are converted by the geti
function to Int
s so that they can be added. I've thought about an other solution which might be:
eval (geti 'a') (42 :: Int)
but that is not possible for me.
So in general my question is: is there any way to make this simpler or implement it more elegant?
This is the code:
-- A static function only used to resolve some demo data
geti :: Char -> Int
geti c | c == 'x' = 42
| c == 'y' = 21
| c == 'z' = 10
| otherwise = 0
-- Here comes the problem:
class Eval t1 t2 where
eval :: t1 -> t2 -> Int
instance Eval Int Int where
eval a b = a + b
instance Eval Int Char where
eval a c = a + (geti c)
instance Eval Char Int where
eval c b = (geti c) + b
instance Eval Char Char where
eval c1 c2 = (geti c1) + (geti c2)
P.S.: I've also tried to combine the solution from here with an "generic" (yes, it's Java language, but I'm new to Haskell ... sry) function but that didn't work ...
Upvotes: 1
Views: 157
Reputation: 229583
I think it would be more straight forward to build a type class for "can be converted to Int
" and use that to implement eval
:
class Intable a where
intify :: a -> Int
instance Intable Int where
intify = id
instance Intable Char where
intify = geti
eval :: (Intable a, Intable b) => a -> b -> Int
eval a b = intify a + intify b
Upvotes: 7