<*>如何使用Function Applicative?

D. *_*oso 2 haskell applicative reader

我试图弄清楚lambda演算为什么以下代码的函数结果

(,) <$> (+1) <*> (+1)
Run Code Online (Sandbox Code Playgroud)

类型为Num a => a - >(a,a)而不是Num a => a - > a - >(a,a)

这就是我所拥有的,我做了一些可怕的错误,或者<*>只是这样连接?

( \x, y -> (,) x y ) <$> ( \x -> x + 1 ) <*> ( \x -> x + 1 )

-- fmap applies first

(\x y -> (,) ((+1) x) y ) <*> ( \x -> x + 1 ) -- substituted the lambda with (+1) for better clarity

-- then goes apply

( \x y -> (,) ((+1) x) ((+1) y) )
Run Code Online (Sandbox Code Playgroud)

lambda的参数如何统一以及在什么时候?

fre*_*yle 5

让我们看看你的例子中的类型:

(,)            <$> (+1)            <*> (+1)
^                  ^                   ^
|                  |                   |
a -> b -> (a, b)   Num a => a -> a     Num a => a -> a
Run Code Online (Sandbox Code Playgroud)

Rhs of Rhs (<$>)和Rhs/Lhs (<*>)必须是申请函.你的算子是Num a => (->) a(monad Reader).

那么,(<$>)申请后会是什么类型(伪代码):

a -> b -> (a, b) <$> Num a => (->) a a ==> Num a => (->) a (b -> (a, b))
Run Code Online (Sandbox Code Playgroud)

之后(<*>)(伪代码):

Num a => (->) a (b -> (a, b)) <*> Num a => (->) a a ==> Num a => (->) a (a, a)
Run Code Online (Sandbox Code Playgroud)

Num a => (->) a (a, a)等同于Num a => a -> (a, a).


正如@chi写的那样,(<*>)类型的实现(->) r是:

(<*>) :: (->) r (a -> b) -> (->) r a -> (->) r b
f <*> g = \r -> f r (g r)
Run Code Online (Sandbox Code Playgroud)

并且,如果您申请,您将得到:

(\x y -> (,) x y) <$> (\r -> r + 1) <*> (\r -> r + 1) =
= (\r y -> (,) (r + 1) y) <*> (\r -> r + 1) =
= \r -> (,) (r + 1) (r + 1)
Run Code Online (Sandbox Code Playgroud)