[Haskell-beginners] Right-associating infix application operators

Daniel Fischer daniel.is.fischer at web.de
Tue Jul 6 07:19:06 EDT 2010


On Tuesday 06 July 2010 13:00:33, Tom Hobbs wrote:
> In people's responses to my serialization questions, I've seen them
> using $.
>
> I didn't know what it was so I've looked it up.  Can someone please
> confirm my understanding of what it does, please?
>
> According to http://en.wikibooks.org/wiki/Haskell/Practical_monads,
> after the second code sample in the "Return Values" section, it seems to
> suggest that $ is only used to avoid using so many brackets.  Which

"only" is an exaggeration, make it "mostly".

Other common uses are

map ($ 3) functionList

and

zipWith ($) functions arguments

it's not necessary, you can get the second from

zipWith id functions arguments

(even using one keystroke less!) and the first from

map (flip id 3) functionList

or

map (\f -> f 3) functionList

As for the zipWith, there's a slight advantage in that ($) stands out more 
than id, without blacking out the rest.
As for the map, well, it takes beginners some time usually to figure out 
what flip id does (and causes surprise that it's even possible, because
flip :: (a -> b -> c) -> b -> a -> c
id :: t -> t
doesn't make it obvious). And the lambda-expression isn't too beautiful 
either.

> seems to make sense, but looking at it's definition in Prelude I really
> can't see why it's useful.
>
> Yitz gave me the code;
>
> fmap (runGet $ readNames n) $ L.hGetContents h
>
> So can I rewrite this without the $ like this?
>
> fmap (runGet (readNames n)) (L.hGetContents h)
>

Yes, that's equivalent.
But with deeper nesting, judicious use of ($) can make the code much more 
readable.

> Is there any additional benefit to using $ than just not having to write
> as many brackets?

See above, it can make things more readable in several ways.
But it shouldn't be overused.

res = f . g . h . i $ j x

is better (IMO) than

res = f $ g $ h $ i $ j $ x

>
> Thanks,
>
> Tom



More information about the Beginners mailing list