SAN
SAN

Reputation: 69

Some errors and difficulties with Haskell function composition

f x = x + 3
g x = x * 3
<interactive>:17:1: error:

    ? Non type-variable argument in the constraint: Num (a -> c)
      (Use FlexibleContexts to permit this)
    ? When checking the inferred type
        it :: forall c a. (Num (a -> c), Num c) => a -> c

I'm getting an error with function composition operator. Why does it not work? f x works, g x works, and even f(g x) works, but f.g x doesn't work.

Upvotes: 0

Views: 96

Answers (1)

lisyarus
lisyarus

Reputation: 15522

The code f . g x doesn't work because it gets parsed as f . (g x). That is, at first g is applied to x, and then you try to get the composition of f with the result of g x.

To make this work, you can surround the composition with parentheses (f . g) x, or use the $ operator, which has the lowest priority of all operators and thus can be used to separate things: f . g $ x.

Upvotes: 6

Related Questions