Meet the Applicative typeclass. It lies in the Control.Applicative module and it defines two methods,
pure and <*>
. It doesn't provide a default implementation for any of them, so we have to define them both if we want something to be an applicative functor.
我试图了解谁在使用
pure
功能。我确实使用 (<*>)
应用仿函数最有用的函数。但我不确定谁真正使用pure
.我读到了
pure (+3) <*> Just 10
之类的东西但可以写成Just (+3) <*> Just 10
也。以上只是我有太多的困惑之一。定义
pure
的真正目的是什么?我什么时候可以使用它(或)谁已经在使用它?
最佳答案
<*> :: f (a -> b) -> f a -> f b
,此运算符接受应用类型中的函数,以及应用类型中的值。因此,此运算符的第一个参数不能只是一个函数,而是必须驻留在应用程序中。pure
function 解决了这里可能出现的问题(例如,想要应用一个不在 applicative 中的函数)。它接受一个当前不在应用程序中的函数,并将其提升到应用程序中。 pure :: a -> f a
(+3) :: Int -> Int
, 和 Just 10 :: Maybe Int
, 你不能因此评估 (+3) <*> Just 10
因为这些类型不起作用; (+3)
必须提升为 Maybe
中的值适用的。
对于 Maybe a
, pure
的定义是 pure = Just
,这就是为什么你可以写成 pure (+3)
或 Just (+3)
--
我将留给您查看<$>
operator :-) 请记住,每个 Applicative 都是一个 Functor。
关于haskell - Applicative Functor中 `pure`的目的是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51512233/