簡體   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