[英]How to write functor instance in haskell with data constructors
我们被给予
type ID = Int
data LST a
= Leaf ID a
| Node ID [LST a]
deriving (Show, Eq)
我如何为 LST 编写一个仿函数实例,这样
instance Functor LST where
fmap = something
您可以让 Haskell 使用DeriveFunctor
扩展[ghc-doc]完成工作:
{-# LANGUAGE DeriveFunctor #-}
type ID = Int
data LST a
= Leaf ID a
| Node ID [LST a]
deriving (Show, Eq, Functor)
通常,有两种方法可以构造Lst a
值,因此首先枚举它们并注意绑定到每个名称的值的类型:
fmap f (Leaf i x) = ... -- f :: a -> b, i :: Int, x :: a
fmap f (Node i xs) = ... -- f :: a -> b, i :: Int, xs :: [a]
假设结果必须以某种方式依赖于f
,那么只有两种选择:
f
应用于x
以获得b
类型的值f
over xs
得到[b]
类型的值。使用它,您可能可以很好地猜测每个定义的右侧应该是什么。 完成后,您可以根据函子定律检查您的定义,特别是,
fmap id (Leaf i x) == id (Leaf i x)
fmap id (Node i xs) == id (Node i xs)
fmap (f.g) (Leaf i x) == fmap f (fmap g (Leaf i x))
fmap (f.g) (Node i xs) == fmap f (fmap g (Node i xs))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.