Haskell - 多参数类型的自定义运算符 class?

Haskell - custom operator for multi-parameter type class?

假设我有一个多参数类型class

class MyClass a b where
    ...

foo :: MyClass a b => a -> b
foo = ...

是否可以为这个关系定义一个自定义中缀符号,这样我就可以写

infixr 1 ?
class a ? b where
    ...

foo :: a ? b => a -> b
foo = ...

是的,使用 TypeOperators 你可以直接给 class 一个符号名称:

{-# Language
    MultiParamTypeClasses,
    TypeOperators #-}

module Example
  ( type (?)
  …
  ) where

class a ? b where
  …

infixr 1 ?

foo :: a ? b => a -> b
foo = …

或者您可以使用 ConstraintKinds:

为命名的 class 创建一个中缀别名
{-# Language
    ConstraintKinds,
    MultiParamTypeClasses,
    TypeOperators #-}

module Example
  ( type (?)
  …
  ) where

class C a b where
  …

type a ? b = C a b

infixr 1 ?

请注意,如果不明确,您可能还需要 ExplicitNamespaces 来导入它。

另一种选择是空子class,如果你希望用额外的约束来扩展它,因为这往往更适合推理:

class (C a b) => a ? b
instance (C a b) => a ? b

infixr 1 ?