删除ad-hoc多态

时间:2017-06-29 13:00:10

标签: 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

1 个答案:

答案 0 :(得分:7)

我认为你真的想要

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

@ F部分指定我们需要fmap仿函数F