简体   繁体   English

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

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

Good day/night everyone! 大家晚上好/晚上好! I have type: 我输入:

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

and I want to write function mapFix :: (a -> b) -> FixItem ma -> FixItem mb . 而且我想编写函数mapFix :: (a -> b) -> FixItem ma -> FixItem mb When I try: 当我尝试:

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

So, I get error: 所以,我得到错误:

    • 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)

How to write mapFix or implement Functor instance for such type (FixItem fixes a to a , not to b , ie fix is a -> a , not a -> b )? 如何编写mapFix或实现此类类型的Functor实例(FixItem将a固定为a ,而不是b ,即固定为a- a -> a ,而不是a- a -> b )?

You can't implement Functor type class for your data type. 您不能为数据类型实现Functor类型类。 It's because of a -> a inside one of your constructors. 这是因为您的构造函数中有a -> a When you have functions, you should be more careful. 具有功能时,应格外小心。 But in short, you have type variable a in contravariant position so you can't implement Functor over this type variable. 简而言之,您将类型变量a放在a相反的位置,因此您无法在此类型变量上实现Functor

Though you can implement Invariant for your data type. 虽然您可以为数据类型实现Invariant式。 Because a in both covariant and contravariant positions, your data type is invariant functor. 因为a两个协变逆变的位置,你的数据类型是不变的仿函数。

Can help you: 可以帮助你:

Example of Invariant Functor? 不变函子的例子?

What is a contravariant functor? 什么是逆函子?

Some blog post 一些博客文章

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

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