gpt4 book ai didi

haskell - fmap的函数组成

转载 作者:行者123 更新时间:2023-12-02 09:16:50 26 4
gpt4 key购买 nike

函数组合的简单定义是:

f ( g x)

(f . g) $ x

现在我有以下示例:

  newtype Compose f g a =
Compose { getCompose :: f (g a) }
deriving (Eq, Show)

instance (Functor f, Functor g) => Functor (Compose f g) where
fmap f (Compose fga) = Compose $ (fmap . fmap) f fga

然后我尝试将不使用组合运算符的 fmap 编写为:

  instance (Functor f, Functor g) => Functor (Compose f g) where
fmap f (Compose fga) = Compose $ fmap f (fmap f fga)

编译器提示:

* Couldn't match type `b' with `g b'
`b' is a rigid type variable bound by
the type signature for:
fmap :: forall a b. (a -> b) -> Compose f g a -> Compose f g b
at D:\haskell\chapter25\src\Twinplicative.hs:11:5
Expected type: f (g b)
Actual type: f b
* In the second argument of `($)', namely `fmap f (fmap f fga)'
In the expression: Compose $ fmap f (fmap f fga)
In an equation for `fmap':
fmap f (Compose fga) = Compose $ fmap f (fmap f fga)
* Relevant bindings include
fga :: f (g a)
(bound at D:\haskell\chapter25\src\Twinplicative.hs:11:21)
f :: a -> b
(bound at D:\haskell\chapter25\src\Twinplicative.hs:11:10)
fmap :: (a -> b) -> Compose f g a -> Compose f g b
(bound at D:\haskell\chapter25\src\Twinplicative.hs:11:5)

如何在没有组合运算符的情况下组合上面的fmap

最佳答案

您提供给 fmap 最左侧应用程序的函数应具有类型 g a -> g b,而您提供的 f 类型为 a -> b。您可以使用 fmapfmap f 将函数 a -> b 提升为 g a -> g b。外部 fmap 的第二个参数应具有类型 f (g a),即 fga 的类型:

instance (Functor f, Functor g) => Functor (Compose f g) where
fmap f (Compose fga) = Compose $ fmap (fmap f) fga

关于haskell - fmap的函数组成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46321812/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com