[Haskell-beginners] f . g or f g or f $ g?

Denis Kasak denis.kasak at gmail.com
Fri Feb 1 23:12:23 CET 2013


On 1 February 2013 20:42, Martin Drautzburg <Martin.Drautzburg at web.de>wrote:

> Hello all
>
> I frequently get confused over f . g vs f g. I do understand the following
>
> With:
>
> g :: a->b
> f :: b ->c
>
> f.g :: a->c
>
> However
>
> f g
>
> is a type error, because then f would have to accept a function (a->b) as
> its
> first parameter, but it only accepts a b.
>
> Is there a way to easily remember when to use f.g and when to use f g
> without
> having to do this type algebra.
>

If you're familiar with the analogous operations in mathematics (function
composition and function application), it should be easy to reason about.

Function application is the act of "calling" the function: passing it an
argument and making it "return" a result. In math, we write function
application with parentheses, i.e.

    cos(pi)

which "returns" (or /has value of/) -1. The equivalent in Haskell would be
written simply as

    cos pi

Function composition on the other hand is the act of combining two
functions (e.g. f1 and f2) so that the resultant function performs both
operations in sequence. You can think of it as combining the functions in a
pipeline so that the output of the first is passed as an argument to the
second. Again, in mathematics, we'd write the composition of f1 and f2 as

    f2 ∘ f1

In Haskell, we would write the same as

    f2 . f1

This is a good mnemonic for remembering the role of (.) since the dot looks
a bit like the small circle used for functional composition in mathematics.

-- 
Denis Kasak
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20130201/453347af/attachment.htm>


More information about the Beginners mailing list