:t pure [] pure [] :: Applicative f => f [a] Prelude> :t pure [] 3 pu-6ren">
gpt4 book ai didi

haskell - 为什么 (pure [] 3) 的类型是 "[a]"?

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

当我检查 ghci 时,我发现了这种行为;

Prelude> :t pure []
pure [] :: Applicative f => f [a]

Prelude> :t pure [] 3
pure [] 3 :: [a]
Prelude> pure [] 3
[]

我不确定为什么会这样,为什么 pure [] 3[a] 的类型?最后一个表达式发生了什么?

最佳答案

简答:此处使用(->) b作为f

pure [] 的类型是 pure []::Applicative f => f [a],正如您最初派生的那样。现在您将其作为函数调用。所以这意味着 Haskell 推断 f ~ Num b => (->) bb3 的类型。我们在这里很幸运,因为 (->) b 确实是 Applicative, it is defined as [src] 的一个实例:

instance Applicative ((->) a) where
<b>pure = const</b>
(<*>) f g x = f x (g x)
liftA2 q f g x = q (f x) (g x)

所以这里的 pure 被解释为 const :: a -> b -> a .因此我们写道:

   pure [] 3
-> const [] 3
-> (\_ -> []) 3
-> []

const 因此忽略了此处的 3,因此返回类型是 [],其中列表可以包含任何类型的项目。

关于haskell - 为什么 (pure [] 3) 的类型是 "[a]"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57593337/

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