【问题标题】:Haskell printing strings stdoutHaskell 打印字符串标准输出
【发布时间】:2013-11-28 06:37:36
【问题描述】:

我需要打印 powerset 中的元素。现在我的代码输出是这样的:

"a"
"ab"
"b"
"x"
"xy"
"xyz"
"xz"
"y"
"yz"
"z"

但是,我需要输出没有引号,像这样:

a
ab
b
x
xy
xyz
xz
y
yz
z

这就是我所拥有的。如何修复它以获得正确的输出?

import Data.List
powerset = foldr (\x acc -> acc ++ map (x:) acc) [[]]

main = do
    numCases <- getLine
    repl $ (read numCases :: Int)

repl num = do
    if(num == 0) then return ()
    else do
        size <- getLine
        input <- getLine
        let ret = tail $ sort $ powerset input
        mapM (\x -> print x) ret
        repl $ num-1

【问题讨论】:

    标签: haskell output user-input


    【解决方案1】:

    First (\x -&gt; f x) 等价于 eta-reduction 的普通 f(在几乎所有情况下)。因此,您可以将mapM (\x -&gt; print x) 重写为mapM print

    要删除引号,您应该使用函数putStrLn 而不是print 函数。 print 中的引号来自print = putStrLn . showshow 是一个函数,它以一种可以(如果定义了合适的实例)可以用read 读回的方式打印出值。因此,您不希望(或不需要)用于您的用例的字符串上的引号。

    【讨论】:

    • putStrLn 做到了。谢谢你的解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    • 2013-05-01
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 2021-09-05
    • 2012-09-02
    相关资源
    最近更新 更多