以格式打印元组中的值

时间:2014-05-02 01:02:38

标签: haskell

这个问题可能看起来很傻,但请耐心等待我

我打算将元组打印为

String1 - 10

Sritng2 - 20

String3 - 30

但如果我

putStrLn $ show(tuples)

它给我输出为[(“String”,10),(“String”,20),(“String”,30)]

3 个答案:

答案 0 :(得分:1)

Show实例用于将数据转换为字符串,然后可以使用Read实例将其直接解析回数据类型。如果你想做这样的事情,你需要编写自己漂亮的打印功能:

pprintTuple :: (Show a, Show b) => (a, b) -> String
pprintTuple (a, b) = show a ++ " - " ++ show b

使用此功能,您可以将每个元组转换为字符串,然后使用putStrLnmapM_一次打印出一行:

mapM_ putStrLn $ map pprintTuple tuples

mapM_map类似,但它适用于monadic函数,并且还会丢弃返回的任何值。由于putStrLn没有返回()以外的值,因此您想在此处使用它。

答案 1 :(得分:1)

根据show给出的输出和您的预期输出,看起来像这是您想要的:

putTuples ts = mapM_ putStrLn $ zipWith showTuple ts [1..]
    where
        showTuple (str, num) seq = str ++ show seq ++ " - " ++ show num

测试:

> let ts = [("String",10),("String",20),("String",30)]
> putTuples ts
String1 - 10
String2 - 20
String3 - 30

答案 2 :(得分:1)

还有另一种打印元组的方法,它提供更多控制但需要导入Text.Printf

示例:

> let xs = [("String1",10),("String2",20),("String3",30)]
> mapM_ (\(x, y) -> printf "%s - %d\n" x y) xs
String1 - 10
String2 - 20
String3 - 30

当然,你可以使lambda成为一个命名函数。 我觉得有很多东西需要打印。