运营商超载

Asl*_*986 18 haskell operator-overloading

我想定义一个+-+在这里工作的运算符(调用它):

if a,b are Char    => a +-+ b = [a][b]
if a,b are Integer => a +-+ b = a+b
Run Code Online (Sandbox Code Playgroud)

我尝试过:

class Summable a where
    (+-+)       :: a -> a -> b

instance Summable Integer where
    a +-+ b     = a + b

instance Summable Char where
    a +-+ b     = [a] ++ [b]
Run Code Online (Sandbox Code Playgroud)

但是我得到了错误:

Couldn't match type `b' with `Integer'....
Couldn't match type `b' with `[Char]' ....
Run Code Online (Sandbox Code Playgroud)

是否有可能做到这一点?怎么样?

huo*_*uon 25

问题是b无法从实例确定类型变量,即使它是固定的.(有一个像这样的自由变量需要函数返回任何类型的东西,即undefined.)

你能给出+-+类型a -> a -> a吗?如果是这样,那就这样做.(但看起来这是不可能的.)

否则,您可以使用函数依赖项,以便实例指定结果类型或类型族,以便实例化的其中一个属性是结果类型.

对于函数依赖,代码可能如下所示:

{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}

class Summable a result | a -> result where
  (+-+) :: a -> a -> result

instance Summable Char String where
  a +-+ b = [a] ++ [b]

instance Summable Integer Integer where
  a +-+ b = a + b
Run Code Online (Sandbox Code Playgroud)

对于类型系列,它将是:

{-# LANGUAGE TypeFamilies #-}

class Summable a where
  type Result a
  (+-+) :: a -> a -> Result a

instance Summable Char where
  type Result Char = String
  a +-+ b = [a] ++ [b]

instance Summable Integer where
  type Result Integer = Integer
  a +-+ b = a + b
Run Code Online (Sandbox Code Playgroud)

(感谢Vitus和Vladimir Matveev修复我所犯的各种错误!:))