Haskell正确使用show function

时间:2011-10-21 12:04:23

标签: haskell show

所以我在GHCI中这样做

Prelude> show (5, 6)

会得到我

Prelude> "(5,6)"

但是我想打印出来(5,6)而中间没有逗号。所以我试过

Prelude> show (5 6)

我希望得到

Prelude> (5 6)

但它让我失望:

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 个答案:

答案 0 :(得分:6)

(5 6)不是有效的Haskell表达式:它正在尝试将5作为函数应用于6。如果要打印两个值而不使用逗号,请为其定义一个函数:

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

然后尝试uncurry showPair (5, 6)showPair 5 6

答案 1 :(得分:1)

show (5, 6)有效,因为(5, 6)是一对值。但是show (5 4)不起作用,因为(5 4)并不代表Haskell中的任何内容。 ghci正试图将5应用于4,就像5是一个函数一样。

答案 2 :(得分:1)

您还可以从(a,b)创建一个新类型:

newtype Tuple a b = Tuple (a, b)

从Show中得出它:

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

然后在GHC:

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

这种方法很酷,但现在,使用(a,b)操作的函数不能与元组一起使用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))

因此,请确保您要使用什么:编写新类型或函数showPair

答案 3 :(得分:0)

修正了它,以便上面的showPair函数现在可以正常工作。

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

*Main> showPair (1,2)
"(1 2)"

答案 4 :(得分:-1)

我的Haskell有点生疏(并且在这个系统上没有Hugs),但我认为这样的事情会这样做:

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