Haskell:编写一个函数来添加由函数映射到Ints的Ints和Chars

myt*_*hbu 1 haskell

代码bellow适用于这样的输入:

*Main> eval 'y' (21 :: Int)
42
*Main> eval 'x' 'a'
42
*Main> eval (21 :: Int) (21 :: Int)
42
*Main> eval (42 :: Int) 'a'
42
Run Code Online (Sandbox Code Playgroud)

这背后的一般问题是我想添加两件事.添加到Ints并不难实现(它已经内置).但是我有一个给定的函数(这里geti)将Chars 解析为Ints和my add-function现在应该添加两个Ints以及Int组合Char(在每个排列中).的CharS被转换geti函数Int是如此,它们可以被添加.我考虑过另一种解决方案可能是:

eval (geti 'a') (42 :: Int)
Run Code Online (Sandbox Code Playgroud)

但这对我来说是不可能的.

所以一般来说我的问题是:有没有办法让这个更简单或实现它更优雅?

这是代码:

-- 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)
Run Code Online (Sandbox Code Playgroud)

PS:我也尝试将这里的解决方案与"通用"(是的,它的Java语言,但我是Haskell ... sry的新手)相结合,但这不起作用......

sth*_*sth 7

我认为为"可以转换为Int" 构建类型类并使用它来实现更直接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
Run Code Online (Sandbox Code Playgroud)