gpt4 book ai didi

haskell - 为什么 f <$> g <$> x 等价于 (f . g) <$> x 虽然 <$> 不是右结合的?

转载 作者:行者123 更新时间:2023-12-04 00:38:02 25 4
gpt4 key购买 nike

为什么是 f <$> g <$> x相当于 (f . g) <$> x虽然 <$>不是右结合吗?

(这种等价在 a popular idiom 和普通 $ 中有效,但目前 $ 是右结合的!)
<*><$> 具有相同的关联性和优先级,但行为不同!

例子:

Prelude Control.Applicative> (show . show) <$> Just 3
Just "\"3\""
Prelude Control.Applicative> show <$> show <$> Just 3
Just "\"3\""
Prelude Control.Applicative> pure show <*> pure show <*> Just 3

<interactive>:12:6:
Couldn't match type `[Char]' with `a0 -> b0'
Expected type: (a1 -> String) -> a0 -> b0
Actual type: (a1 -> String) -> String
In the first argument of `pure', namely `show'
In the first argument of `(<*>)', namely `pure show'
In the first argument of `(<*>)', namely `pure show <*> pure show'
Prelude Control.Applicative>
Prelude Control.Applicative> :i (<$>)
(<$>) :: Functor f => (a -> b) -> f a -> f b
-- Defined in `Data.Functor'
infixl 4 <$>
Prelude Control.Applicative> :i (<*>)
class Functor f => Applicative f where
...
(<*>) :: f (a -> b) -> f a -> f b
...
-- Defined in `Control.Applicative'
infixl 4 <*>
Prelude Control.Applicative>

来自 <$> 的定义, 我希望 show <$> show <$> Just 3失败,也是。

最佳答案

Why is f <$> g <$> x equivalent to (f . g) <$> x?



这与其说是仿函数的事情,不如说是 Haskell 的事情。它起作用的原因是函数是仿函数。两个 <$>运算符在不同的仿函数中工作!
f <$> g实际上与 f . g 相同,所以你要问的等价性比 f <$> (g <$> x) ≡ f . g <$> x更微不足道。 .

关于haskell - 为什么 f <$> g <$> x 等价于 (f . g) <$> x 虽然 <$> 不是右结合的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30911093/

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