简体   繁体   中英

Haskell Function Composition (.) vs Function Application ($)

I'm going through this source code for learning.

On line 81 I see the following code:

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

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 is (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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM