删除ad-hoc多态性

nic*_*las 1 haskell functor category-theory

在haskell中删除ad-hoc多态的最佳方法是什么?

80%的时间,我不需要fmap多态Functor 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
Run Code Online (Sandbox Code Playgroud)

chi*_*chi 7

我想你真的想要

{-# LANGUAGE TypeApplications #-}
r = fmap @ F f Z
Run Code Online (Sandbox Code Playgroud)

@ F部分指定我们想要的fmap仿函数F.