在用空格Haskell分隔的一行中打印非字符串变量



我有两个int变量,希望将它们打印在一行上,用空格分隔。如何在Haskell中实现这一点?

main :: IO ()
main = do 
let one = 1
let two = 2
print ( one, two ) -- 1 option
mapM_ (putStr . show) [one, two]  -- 2 option
print (one ++ " " ++ two)  -- 3 option

1个选项给出结果:(1,2(

2选项给出结果:12

3选项给出错误:

No instance for (Num [Char]) arising from the literal '2'

那么,如何在一行中打印两个值,用空格分隔?

您需要将元素转换为String,例如使用show:

print (showone ++ " " ++showtwo)

您还可以使用intercalate :: [a] -> [[a]] -> [a]在字符串之间添加分隔符,因此:

import Data.List(intercalate)
main :: IO ()
main = do
putStrLn ((intercalate " ". map show) [one, two])

这使得将其扩展到任意数量的元素变得容易。

此外(如果你知道C等其他语言(,你可能会发现printf也很容易使用-它会给你一些灵活性-你的例子可能是

printf "%d %dn" one two

有一点";魔术;继续,以便您可以使用它返回String或在IO中使用它直接打印到控制台:

ghci> printf "%d %dn" 1 2
1 2
ghci> printf "%d %dn" 1 2 :: String     
"1 2n"       
ghci> :t it
it :: String                                          

最新更新