去除临时多态性

removing ad-hoc polymorphism

删除 haskell 中的临时多态性的最佳方法是什么?

80% 的时间,我不需要 fmapFunctor f 中是多态的,我实际上知道我将它应用于哪个实例。用特定实例替换它给我:

像在范畴论中一样,将函子 F 应用于 haskell 中的态射的最佳方法是什么?

-- F is a functor : it maps objects of * to objects of *
data F r = Z | Suc r

-- F is a functor : it maps arrows of *  to arrows of *
-- generic fmap will be found for this type, I inherit much code for free, great
instance Functor F where
  fmap f Z       = Z
  fmap f (Suc n) = Suc (f n)

-- But I care writing code specific for this functor only
-- Applies F for arrows of *
fmapF = fmap :: (a -> b) -> (F a -> F b)

-- an arrow in *, aka a function -- (and also a value as * is CCC)
f = id :: a -> a

-- works for values F a, not any functor f
r = fmapF f Z :: F a
r' = fmap f "hi" -- as opposed to

我想你真的想要

{-# LANGUAGE TypeApplications #-}
r = fmap @ F f Z

@ F 部分指定我们想要函子 F.

fmap