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)
5 Answers
(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.
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.
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.
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)"
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) ++ ")"