有没有办法在ghc中重载并置?

Is there a way to overload juxtaposition in ghc?

我正在尝试在 Haskell 中设计一种嵌入式语言,如果可能的话,我想为并置赋予自定义含义,通常表示函数应用。 或者,几乎等同地,我想定义一个空白运算符,它具有正常的可定义运算符优先级。

类似

( ) x y = x * y

然后允许将乘法 3 * 4 写为 3 4

GHC 中有什么方法(使用任何必要的扩展)来实现这个吗?

事实上,是的!

{-# LANGUAGE FlexibleInstances #-}
module Temp where

instance Num a => Num (a -> a) where
  fromInteger n = (fromInteger n *)
  n + m = \x -> n x + m x
  -- ...

然后在 ghci 中:

λ :l Temp
...
λ 3 (4 :: Int) :: Int
12
λ let _4 = 4 :: Int
λ 3 _4 :: Int
12
λ (3 + 4) (2 :: Int) :: Int
14

Haskell 中的符号 01 等被重载 - 0 :: Num a => a - 它们可以表示任何具有 Num 实例的东西。因此,通过为函数 Num a => a -> a 定义一个 Num 实例,我们现在有 3 :: Num a => a -> a