在由 space Haskell 分隔的一行中打印非字符串变量

Print non-string variables in one line separated by space Haskell

我有两个 int 变量,想将它们打印在一行上,用 space 分隔。如何在 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'

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

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

print (<b>show</b> one ++ " " ++ <b>show</b> two)

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

import Data.List(intercalate)

main :: IO ()
main = do
    putStrLn ((<b>intercalate " "</b> . map show) [one, two])

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

另外(如果您了解 C 等其他语言)您可能会发现 printf 也易于使用 - 它会给您一些灵活性 - 您的示例可以是

printf "%d %d\n" one two

有一些“魔法”正在发生,因此您可以使用它取回 String 或在 IO 中使用它直接打印到控制台:

ghci> printf "%d %d\n" 1 2
1 2

ghci> printf "%d %d\n" 1 2 :: String     
"1 2\n"       

ghci> :t it
it :: String