【问题标题】:Print non-string variables in one line separated by space Haskell在一行中打印非字符串变量,以空格分隔 Haskell
【发布时间】:2021-06-25 06:49:08
【问题描述】:

我有两个 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'

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

【问题讨论】:

  • 嗨 - 我知道这很令人困惑,因为大多数其他语言都使用 print 但你应该尽量避免这种情况(使用 putStrLn 代替)因为它总是会添加一个 show 这通常是不是你想要的 - 使用putStrLn 会迫使你考虑如何格式化(因为它只适用于Strings)

标签: variables haskell printing io output


【解决方案1】:

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

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

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

import Data.List(intercalate)

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

这使得它可以很容易地扩展到任意数量的元素。

【讨论】:

  • @vytaute: intercalate " "Prelude 中也称为unwords,例如:putStrLn $ unwords $ map show [one, two]。如果变量类型不同,可以使用[show one, show two] 代替map show […]。另请注意,它的表亲unlinesintercalate "\n" 并不完全相同,因为unlines 附加了一个额外的"\n"
【解决方案2】:

另外(如果您知道 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                                          

【讨论】:

    猜你喜欢
    • 2014-01-07
    • 2020-01-22
    • 2016-12-10
    • 2010-12-01
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    相关资源
    最近更新 更多