1

So I am doing this in GHCI

Prelude> show (5, 6)

will get me

Prelude> "(5,6)"

But I want to print out (5, 6) without the comma in between. So I tried

Prelude> show (5 6)

and I expect to get

Prelude> (5 6)

But it fails me with:

No instance for (Num (a1 -> a0))
      arising from the literal `5'
    Possible fix: add an instance declaration for (Num (a1 -> a0))
    In the expression: 5
    In the first argument of `show', namely `(5 4)'
    In the expression: show (5 4)
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
nobody
  • 2,709
  • 6
  • 35
  • 37
  • filter (notElem ",'") (show (5,' ', 6)) seems to do the trick, there should be a better way. – nobody Oct 21 '11 at 12:28
  • seems slightly related to http://stackoverflow.com/questions/7851275/how-to-create-instance-of-read-for-a-datatype-in-haskell/7852258#7852258 – hvr Oct 21 '11 at 17:43

5 Answers5

7

(5 6) is not a valid Haskell expression: it's trying to applying 5 as a function to 6. If you want to print two values without a comma in between, define a function for that:

showPair x y  =  "(" ++ show x ++ " " ++ show y ++ ")"

Then try uncurry showPair (5, 6) or just showPair 5 6.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
2

show (5, 6) works because (5, 6) is a pair of value. But show (5 4) doesn't work because (5 4) doesn't mean anyting in Haskell. ghci is trying to apply 5 to 4 as if 5 were a function.

WilQu
  • 7,131
  • 6
  • 30
  • 38
2

You also make a new type from (a,b) like this:

newtype Tuple a b = Tuple (a, b)

And derive it from Show like this:

instance (Show a, Show b) => Show (Tuple a b) where
  show (Tuple (a, b)) = "(" ++ show a ++ " " ++ show b ++ ")"

Then in GHC:

*Main> Tuple (1,2)
(1 2)

This method is cool, but now, functions that operate with (a,b) don't work with Tuple a b:

*Main> fst (1,2)
1
*Main> fst (Tuple (1,2))

<interactive>:1:6:
Couldn't match expected type `(a0, b0)'
            with actual type `Tuple a1 b1'
    In the return type of a call of `Tuple'
    In the first argument of `fst', namely `(Tuple (1, 2))'
    In the expression: fst (Tuple (1, 2))

So be sure what do you want to use: writing new type or a function showPair.

franza
  • 2,297
  • 25
  • 39
1

Fixed it so that the above showPair function now works.

showPair :: (Int,Int) -> String
showPair p = "(" ++ show (fst p) ++ " " ++ show (snd p) ++ ")"

*Main> showPair (1,2)
"(1 2)"
Bylextor
  • 213
  • 3
  • 7
0

My Haskell is a little rusty (and don't have Hugs on this system), but i think something like this will do it:

showPair :: (Int,Int) -> String
showPair p = "(" ++ show (fst p) ++ " " ++ show (snd p) ++ ")"
Community
  • 1
  • 1
Remy
  • 329
  • 1
  • 10