关于++来连接东西

时间:2011-07-22 22:18:55

标签: haskell

给出以下函数签名:

concatThings :: (Show a) => a -> String -> String
concatThings any str2 = str2 ++ (show any)

如果运行concatThings "there" "hi",则结果为:"hi\"there\"",但我想要的只是"hithere"

我怎样才能使用此功能签名获得“hithere”?

2 个答案:

答案 0 :(得分:4)

使用此功能签名,您不能。您必须要么摆脱show,将功能减少到

concatStrs :: String -> String -> String
concatStrs = flip (++)

或引入新的类型来替换Show

答案 1 :(得分:3)

您可以将字符串换成新类型,并为其提供一个简单的Show实例:

newtype PartialString = PartialString String

instance Show PartialString where
    show PartialString str = str

然后将包装好的字符串传递给concatThings函数:

let pstr1 = PartialString str1 in concatThings pstr1 str2