Haskell Functor implied law

后端 未结 4 1230
清酒与你
清酒与你 2021-02-07 02:49

Typeclassopedia says:

\"A similar argument also shows that any Functor instance satisfying the first law (fmap id = id) will automatically satisfy the second law as well

4条回答
  •  太阳男子
    2021-02-07 03:28

    Using seq, we can write an instance which satisfies the first rule but not the second one.

    data Foo a = Foo a
        deriving Show
    
    instance Functor Foo where
        fmap f (Foo x) = f `seq` Foo (f x)
    

    We can verify that this satisfies the first law:

    fmap id (Foo x)
    = id `seq` Foo (id x)
    = Foo (id x)
    = Foo x
    

    However, it breaks the second law:

    > fmap (const 42 . undefined) $ Foo 3
    Foo 42
    > fmap (const 42) . fmap undefined $ Foo 3
    *** Exception: Prelude.undefined
    

    That said, we usually ignore such pathological cases.

提交回复
热议问题