我有以下类型data Summish a b = First a | Second b。
如何为其编写 Functor 实例?
我试过
instance Functor (Summish a) where
fmap f (Second a) = Second (f a)
Run Code Online (Sandbox Code Playgroud)
最简单的方法是让编译器为你做(派生)它:
{-# LANGUAGE DeriveFunctor #-}
data Summish a b
= First a
| Second b
deriving Functor
Run Code Online (Sandbox Code Playgroud)
这仅适用于您在GHC 中启用了派生函子扩展(用于 GHCi )。:set -XDeriveFunctor
所以我猜你想/需要手动推导它。
正如其他人所说,您只需要案例First即可使其详尽无遗:
data Summish a b
= First a
| Second b
instance Functor (Summish a) where
fmap f (First b) = First b
fmap f (Second a) = Second (f a)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
83 次 |
| 最近记录: |