繁体   English   中英

如何编写map / fmap模拟(a-> b)-> F ma-> F mb

[英]How to write map/fmap analogue (a->b) -> F m a -> F m b

大家晚上好/晚上好! 我输入:

data FixItem m a = KeepItem|SkipItem|FixItem (m (a -> a))
fixItem f = FixItem $ pure f

而且我想编写函数mapFix :: (a -> b) -> FixItem ma -> FixItem mb 当我尝试:

mapFix f SkipItem = SkipItem -- good
mapFix f KeepItem = fixItem f -- error "rigid type"!!!
mapFix f (FixItem mf) = FixItem $ pure (.) <*> (pure f) <*> mf -- too!

所以,我得到错误:

    • Couldn't match type ‘b’ with ‘a’
      ‘b’ is a rigid type variable bound by
        the type signature for:
          mapFix :: forall (m :: * -> *) a b.
                    Applicative m =>
                    (a -> b) -> FixItem m a -> FixItem m b
        at src/test.hs:235:11
      ‘a’ is a rigid type variable bound by
        the type signature for:
          mapFix :: forall (m :: * -> *) a b.
                    Applicative m =>
                    (a -> b) -> FixItem m a -> FixItem m b
        at src/test.hs:235:11
      Expected type: b -> b
        Actual type: a -> b
    • In the first argument of ‘fixItem’, namely ‘f’
      In the expression: fixItem f
      In an equation for ‘mapFix’: mapFix f KeepItem = fixItem f
    • Relevant bindings include
        f :: a -> b (bound at src/test.hs:236:8)
        mapFix :: (a -> b) -> FixItem m a -> FixItem m b
          (bound at src/test.hs:236:1)

如何编写mapFix或实现此类类型的Functor实例(FixItem将a固定为a ,而不是b ,即固定为a- a -> a ,而不是a- a -> b )?

您不能为数据类型实现Functor类型类。 这是因为您的构造函数中有a -> a 具有功能时,应格外小心。 简而言之,您将类型变量a放在a相反的位置,因此您无法在此类型变量上实现Functor

虽然您可以为数据类型实现Invariant式。 因为a两个协变逆变的位置,你的数据类型是不变的仿函数。

可以帮助你:

不变函子的例子?

什么是逆函子?

一些博客文章

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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