为什么(纯[] 3)的类型是“ [a]”?

use*_*328 2 haskell

当我检查ghci时,我发现了这种现象。

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

Prelude> :t pure [] 3
pure [] 3 :: [a]
Prelude> pure [] 3
[]
Run Code Online (Sandbox Code Playgroud)

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

Wil*_*sem 9

答案很简单:它使用的(->) bf在这里。

的类型pure []pure [] :: Applicative f => f [a]您首次导出的。现在,您将其称为函数。因此,这意味着Haskell f ~ Num b => (->) bb的类型进行推断3。我们在这里很幸运,因为(->) b确实是的一个实例Applicative,它被定义为[src]

instance Applicative ((->) a) where
    pure = const
    (<*>) f g x = f x (g x)
    liftA2 q f g x = q (f x) (g x)
Run Code Online (Sandbox Code Playgroud)

因此,此处的pure解释为const :: a -> b -> a。因此,我们写了:

   pure [] 3
-> const [] 3
-> (\_ -> []) 3
-> []
Run Code Online (Sandbox Code Playgroud)

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