gpt4 book ai didi

haskell - 对作为haskell中Functor实例的函数感到困惑

转载 作者:行者123 更新时间:2023-12-03 11:03:44 24 4
gpt4 key购买 nike

Functor 中 fmap 的类型是:

fmap :: Functor f => (a -> b) -> f a -> f b
看起来,首先将函数 (a -> b) 应用于 f a 的参数以创建 b 类型的结果,然后将 f 应用于它,结果是 f b
使用 Maybe a例如:
 fmap show (Just 1)
result is : Just "1"
和说的一样:
Just (show 1)
但是当 (->)用作仿函数(在 Control.Monad.Instances 中)
import Control.Monad.Instances
(fmap show Just) 1
result is : "Just 1"
也就是说, Just首先应用,然后 show被申请;被应用。在另一个例子中,结果是一样的:
 fmap (*3) (+100) 1
result is 303
为什么不 *3首先,然后 +100 ?

最佳答案

fmap (->) r 的实例(即函数)实际上只是组合。来自 the source itself :

instance Functor ((->) r) where
fmap = (.)

因此,在您的示例中,我们可以替换 fmap(.) , 并做一些变换
fmap (*3) (+100) 1 => 
(.) (*3) (+100) 1 =>
(*3) . (+100) $ 1 => -- put (.) infix
(*3) (1 + 100) => -- apply (+100)
(1 + 100) * 3 -- apply (*3)

也就是说, fmap for 函数从右到左组合它们(与 (.) 完全相同,这是明智的,因为它是 (.) )。

换一种方式来看(用于(双重)确认!),我们可以使用类型签名:
-- general fmap
fmap :: Functor f => (a -> b) -> f a -> f b

-- specialised to the function functor (I've removed the last pair of brackets)
fmap :: (a -> b) -> (r -> a) -> r -> b

所以首先是 r 类型的值(第三个参数)需要转换为 a 类型的值(通过 r -> a 函数),因此 a -> b函数可以将其转换为 b 类型的值(结果)。

关于haskell - 对作为haskell中Functor实例的函数感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10294272/

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