haskell - 运算符重载

标签 haskell operator-overloading

我想定义一个在此工作的运算符(称为 +-+ ):

if a,b are Char    => a +-+ b = [a][b]
if a,b are Integer => a +-+ b = a+b

我试过:
class Summable a where
    (+-+)       :: a -> a -> b

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

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

但我得到了错误:
Couldn't match type `b' with `Integer'....
Couldn't match type `b' with `[Char]' ....

是否有可能做到这一点?如何?

最佳答案

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

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

否则,您可以使用 functional dependencies ,以便实例指定结果类型,或 type families ,因此实例化的属性之一是结果类型。

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

{-# 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

对于类型族,它会像:
{-# 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

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

关于haskell - 运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12076475/

相关文章:

C++ operator< 重载结构

haskell - 同一事件多次发生

c++ - 在 C++ 中显式转换为 native 类型

F#:为什么在重载成员函数时需要提供参数类型?

haskell - 解析器跳过行

c++ - 使用类特定的 set_new_handler

c++ - 字符串的运算符重载

haskell - 为什么 "cabal build"与 "make"相比这么慢?

haskell - 在类型类中使用实例类型参数

ubuntu - WSL : Cabal could not resolve dependencies. 容器,二进制