开发者

. versus $ in haskell [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Haskell: difference between . (dot) a开发者_如何学编程nd $ (dollar sign)

Ok I understand that this:

f(g(x))

can be rewritten:

f $ g(x)

and can also be rewritten:

f . g(x)

What I don't fully grasp is where the two DO NOT overlap in functionality. I conceptually understand that they don't fully overlap, but could someone clarify this for me once and for all?


Prelude> :t ($)
($) :: (a -> b) -> a -> b
Prelude> :t (.)
(.) :: (b -> c) -> (a -> b) -> a -> c

$ applies a function to a value. . composes two functions.

So I can write f $ g x which is "apply f to (g of x)" or f . g $ x which is "apply the composition of f and g to x". One common style is to pile up dots on the left with a dollar trailing. The reason is that f $ g $ x means the same thing as f . g $ x but the expression f $ g on its own is often meaningless (in fact, possibly a type error) while the expression f . g means "the composition of f and g"


Additionaly to what was already said, you need the $ as "function application glue" in cases like this:

map ($3) [(4+),(5-),(6*),(+4),(*5),(^6)]
--[7,2,18,7,15,729] 

Neither (.3) nor (3) will work in the example.


"f $ g x" cannot be rewritten to "f . g x". In fact, the compiler won't even accept the second function, because "(.)" has the type "(b -> c) -> (a -> b) -> (a -> c)". I.e the second argument must be a function, but "g x" is a value not a function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜