[英]Haskell Function Composition (.) vs Function Application ($)
I'm going through this source code for learning.我正在通过此源代码进行学习。
On line 81 I see the following code:在第 81 行,我看到以下代码:
MaybeT . fmap Just $ locked .= False
I was puzzled by the use of the function composition so I loaded it in my repl and replaced it with function application我对函数组合的使用感到困惑,所以我将它加载到我的 repl 中并用函数应用程序替换它
MaybeT $ fmap Just $ locked .= False
I'm very surprised these two pieces of code give the exact result.我很惊讶这两段代码给出了确切的结果。
Control.Monad.State.Class.MonadState Game m => MaybeT m ()
In fact, I can understand how function application ($)
is producing this result but I'm floored as to how function composition (.)
is producing this result.事实上,我可以理解函数应用程序
($)
如何产生这个结果,但我对函数组合(.)
如何产生这个结果感到困惑。 The signatures of these two functions are different and I think they should clearly produce different results if one replaces the other.这两个函数的签名是不同的,我认为如果一个替换另一个,它们应该会产生不同的结果。
:t (.) :: (b -> c) -> (a -> b) -> a -> c
:t ($) :: (a -> b) -> a -> b
Can someone explain to me why the ($)
and (.)
are interchangeable in this case.有人可以向我解释为什么
($)
和(.)
在这种情况下可以互换。
.
has a higher precedence than $
:具有比
$
更高的优先级:
> :info ($)
($) :: (a -> b) -> a -> b -- Defined in ‘GHC.Base’
infixr 0 $
> :info (.)
(.) :: (b -> c) -> (a -> b) -> a -> c -- Defined in ‘GHC.Base’
infixr 9 .
So a $ b $ c $ d
is a $ (b $ (c $ d))
, but a . b . c $ d
所以
a $ b $ c $ d
是a $ (b $ (c $ d))
,但是a . b . c $ d
a . b . c $ d
a . b . c $ d
is (a . (b . c)) $ d
. a . b . c $ d
是(a . (b . c)) $ d
。
They are not interchangeable.它们不可互换。
What you have is你拥有的是
MaybeT . fmap Just $ locked
MaybeT $ fmap Just $ locked -- you had `dead` here
but because of operator precedence it is really parsed as但由于运算符优先级,它实际上被解析为
(MaybeT . fmap Just) locked -- and
MaybeT $ fmap Just locked
the .
的
.
and $
participate in differently structured expressions here.和
$
在这里参与不同结构的表达式。 To be interchangeable would mean you could replace可互换意味着你可以替换
(MaybeT . fmap Just) locked -- with
(MaybeT $ fmap Just) locked
and clearly this is not the case.显然情况并非如此。
So, swapping .
所以,交换
.
for $
in the same expression produces different results, just as you expected. for
$
在同一个表达式中会产生不同的结果,正如您所期望的。 At the same time two different expressions happen to produce the same result.同时,两个不同的表达式碰巧产生了相同的结果。 Nothing strange there at all, expressions get simplified into equivalent different expressions all the time.
没有什么奇怪的,表达式一直被简化为等效的不同表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.