What exactly does “deriving Functor” do?

前端 未结 2 1638
再見小時候
再見小時候 2021-01-01 11:05

I\'m trying to figure out what exactly are the rules for deriving Functor in Haskell.

I\'ve seen message postings about it, and I\'ve seen test code abo

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-01 11:18

    The code that actually does the deed is, unfortunately, a bit on the hairy side. I believe that's largely because earlier, simpler code would sometimes lead to excessive compilation times. Twan van Laarhoven came up with the current code to address this.

    The derived Functor instance always does the obvious thing. This is usually just fine, but occasionally misses opportunities. For example, suppose I write

    data Pair a = Pair a a deriving Functor
    data Digit a = One a | Two a a deriving Functor
    data Queue a =
        Empty
      | Single a
      | Deep !(Digit a) (Queue (Pair a)) !(Digit a) deriving Functor
    

    This will generate (in GHC 8.2)

    instance Functor Queue where
      fmap ...
      x <$ Empty = Empty
      x <$ Single y = Single x
      x <$ Deep pr m sf = Deep (x <$ pr) (fmap (x <$) m) (x <$ sf)
    

    It's possible to write that last case much better by hand:

      x <$ Deep pr m sf = Deep (x <$ pr) (Pair x x <$ m) (x <$ sf)
    

    You can see the actual derived code using -ddump-deriv.

提交回复
热议问题