haskellfunction-compositiondot-operator

Haskell : why f1 . f2 xy not working?


I'm a bit confused concerning the dot operator. I've got the following code (for testing):

test :: Int -> Int -> Int
test x y = f1 . f2 x y 
           where f1 n = n+1
                 f2 x' y' = x' * y'

And I figured it would first execute (f2 x y) and then f1 on that result, but instead it throws an error. Could anyone tell me the exact definition of the dot operator and what equals f1 . f2 x y? (when written without the dot operator)

Best regards, Skyfe.

EDIT: If the dot operator yields a complete new function I figured the following code should work:

test :: Int -> Int -> Int
test x y = f1 . f2 x
           where f1 n = n+1
                 f2 x' y' = x' + y'

But also that code returns an error.


Solution

  • Infix operators always have lower precedence than function application in Haskell, so this

    f1 . f2 x
    

    parses like this

    f1 . (f2 x)
    

    but, f2 x is not of type function (well, it could be if f2 returns a function, but that is not so in general, or in your problem). Since (.) acts on functions, this won't work.

    Use ($) instead

    f1 $ f2 x