简体   繁体   English

如何使用数据构造函数在 haskell 中编写仿函数实例

[英]How to write functor instance in haskell with data constructors

We are given我们被给予

type ID = Int
data LST a
  = Leaf ID a
  | Node ID [LST a]
    deriving (Show, Eq)

How may I write a functor instance for LST, such that我如何为 LST 编写一个仿函数实例,这样

instance Functor LST where
  fmap = something

You can let Haskell do the work with the DeriveFunctor extension [ghc-doc] :您可以让 Haskell 使用DeriveFunctor扩展[ghc-doc]完成工作:

{-# LANGUAGE DeriveFunctor #-}

type ID = Int
data LST a
  = Leaf ID a
  | Node ID [LST a]
  deriving (Show, Eq, Functor)

There are, in general, two ways to construct an Lst a value, so start by enumerating them and noting the types of values bound to each name:通常,有两种方法可以构造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]

Assuming that the results must depend on f somehow, there are only a couple of options for doing so:假设结果必须以某种方式依赖于f ,那么只有两种选择:

  1. Apply f to x to get a value of type bf应用于x以获得b类型的值
  2. Map f over xs to get a value of type [b] . Map f over xs得到[b]类型的值。

Using this, you can probably make a good guess at what the right-hand side of each definition should be.使用它,您可能可以很好地猜测每个定义的右侧应该是什么。 Once you've done that, you can check your definitions against the functor laws, specifically,完成后,您可以根据函子定律检查您的定义,特别是,

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM