Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

. versus $ in haskell [duplicate]

Tags:

haskell

Possible Duplicate:
Haskell: difference between . (dot) and $ (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?

like image 416
Ramy Avatar asked Feb 02 '11 16:02

Ramy


2 Answers

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"

like image 93
sclv Avatar answered Sep 23 '22 06:09

sclv


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.

like image 31
Landei Avatar answered Sep 23 '22 06:09

Landei