如何编写 Functor 实例
How to write Functor instance
我有以下类型 data Summish a b = First a | Second b
。
如何为其编写Functor实例?
我试过了
instance Functor (Summish a) where
fmap f (Second a) = Second (f a)
这就是您编写 Functor
实例的方式。
问题是,这是完全合法的实例吗?
如果您将 deriving Show
添加到您的数据类型,并且您尝试使用此实例:
> fmap (+ 1) (Second 2)
Second 3
> fmap (+ 1) (First 2)
*** Exception: ...: Non-exhaustive patterns in function fmap
似乎这个 Functor
没有处理 Summish a b
的所有可能值。
最简单的方法是让编译器为你做(推导):
{-# LANGUAGE DeriveFunctor #-}
data Summish a b
= First a
| Second b
deriving Functor
这仅在您在 GHC 中启用了 derive functor extension 时有效(对于 GHCi 使用 :set -XDeriveFunctor
)。
所以我猜你 want/need 手动导出它。
正如其他人所说,您只需要 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)
我有以下类型 data Summish a b = First a | Second b
。
如何为其编写Functor实例?
我试过了
instance Functor (Summish a) where
fmap f (Second a) = Second (f a)
这就是您编写 Functor
实例的方式。
问题是,这是完全合法的实例吗?
如果您将 deriving Show
添加到您的数据类型,并且您尝试使用此实例:
> fmap (+ 1) (Second 2)
Second 3
> fmap (+ 1) (First 2)
*** Exception: ...: Non-exhaustive patterns in function fmap
似乎这个 Functor
没有处理 Summish a b
的所有可能值。
最简单的方法是让编译器为你做(推导):
{-# LANGUAGE DeriveFunctor #-}
data Summish a b
= First a
| Second b
deriving Functor
这仅在您在 GHC 中启用了 derive functor extension 时有效(对于 GHCi 使用 :set -XDeriveFunctor
)。
所以我猜你 want/need 手动导出它。
正如其他人所说,您只需要 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)