Mataba
Mataba

Reputation: 89

Show for a constructor

Why does it complain about this code:

data Point = Point {
              x, y :: Int
            } deriving (Show)

main = print $ Point (15 20)

by saying:

No instance for (Show (Int -> Point))
      arising from a use of `print'
    Possible fix: add an instance declaration for (Show (Int -> Point))

Upvotes: 1

Views: 161

Answers (2)

Thomas M. DuBuisson
Thomas M. DuBuisson

Reputation: 64740

What is Wrong

data Point = Point {
              x, y :: Int
            } deriving (Show)

It might become more obvious if we express the constructor Point as a function:

Point :: Int -> Int -> Point

If you know the syntax of function application then this becomes really clear:

main = print $ Point 15 20

Why This Error

As for why the broken code gets your particular error, consider how this is type-checked. We have the expression:

Point ( ...something... )

And if Point :: Int -> Int -> Point then Point something must be of type Int -> Point (Point applied to any single argument has said type). Now you see how it concludes you are trying to call print on something typed Int -> Point and thus complains about the missing instance - it doesn't even consider the bad expression of (15 20).

Upvotes: 9

Neil Brown
Neil Brown

Reputation: 3558

Your bracketing is wrong. Bracketing the (15 20) makes the compiler treat it as one argument to Point, and you're missing the second. If you remove those brackets to leave Point 15 20 it will work.

Upvotes: 9

Related Questions