Dr *_* DR 3 haskell higher-order-functions applicative
Applicative 通常表现为一种将多参数函数提升为函子并将函子值应用于它的方法。但我想知道是否有一些微妙的额外功能源于它可以通过提升返回函数的函数并一次应用一个函数参数来实现这一点。
想象一下,我们定义了一个基于提升函数的接口,其参数是一个参数元组:
# from Functor
fmap :: (a -> b) -> Fa -> Fb
# from Applicative
pure :: a -> Fa
# combine multiple functor values into a functor of a tuple
tuple1 :: Fa -> F(a)
tuple2 :: Fa -> Fb -> F(a,b)
tuple3 :: Fa -> Fb -> Fc -> F(a,b,c)
(etc ...)
# lift multi-argument functions (that take a tuple as input)
ap_tuple1 :: ((a) -> b) -> F(a) -> Fb
ap_tuple2 :: ((a,b) -> c) -> F(a,b) -> Fc
ap_tuple3 :: ((a,b,c) -> d) -> F(a,b,c) -> Fd
(etc ..)
Run Code Online (Sandbox Code Playgroud)
假设我们为我们可能遇到的每个大小的元组定义了相应的元组函数。这个接口是否与 Applicative 接口一样强大,因为它允许提升/应用于多参数函数但不允许提升/应用于返回函数的函数?显然,可以将元组作为参数的函数进行柯里化,以便可以在应用程序中提升它们,也可以取消柯里化返回函数的函数,以便将它们提升到上面的假设实现中。但在我看来,权力有细微的差别。有什么区别吗?(假设这个问题甚至有意义)
你重新发现了monoidal呈现的Applicative。它看起来像这样:
class Functor f => Monoidal f where
(>*<) :: f a -> f b -> f (a, b)
unit :: f ()
Run Code Online (Sandbox Code Playgroud)
Applicative通过以下方式同构:
(>*<) = liftA2 (,)
unit = pure ()
pure x = x <$ unit
f <*> x = fmap (uncurry ($)) (f >*< x)
Run Code Online (Sandbox Code Playgroud)
顺便说一句,您的ap_tuple功能都只是fmap. 具有多个值的“难”部分是将它们组合在一起。将它们拆分成碎片很“容易”。
| 归档时间: |
|
| 查看次数: |
84 次 |
| 最近记录: |