Is there a way to overload mapping in ghc?
I am trying to create an embedded language in Haskell, and if possible, I would like to specify a custom mapping meaning that usually denotes a function application. Or, almost equivalently, I would like to define a whitespace operator that has the normal definable operator precedence.
Something like
( ) x y = x * y
which will then allow you to write the multiplication 3 * 4
as 3 4
.
Is there any way in GHC (using any extension) to implement it?
source to share
Actually, yes!
{-# LANGUAGE FlexibleInstances #-}
module Temp where
instance Num a => Num (a -> a) where
fromInteger n = (fromInteger n *)
n + m = \x -> n x + m x
-- ...
Then in ghci:
λ :l Temp
...
λ 3 (4 :: Int) :: Int
12
λ let _4 = 4 :: Int
λ 3 _4 :: Int
12
λ (3 + 4) (2 :: Int) :: Int
14
Symbols 0
, 1
etc. overloaded in Haskell - 0 :: Num a => a
- they can represent anything that has an instance Num
. Therefore, by defining an instance Num
for functions Num a => a -> a
, we now have3 :: Num a => a -> a
source to share