Haskell:输出元组列表作为字符串输出 [英] Haskell: Output list of tuples as string output

查看:568
本文介绍了Haskell:输出元组列表作为字符串输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  [(2,a),(1, (1,b),(1,c),(2,dd)] 

放入此字符串输出中

  a 1,2 

b 1

c 1

dd 2

我假设我需要使用unzip和unlines函数。但我也看到了一些使用show函数的解决方案,它使整数字符串。任何想法?

解决方案

将问题分解成多个步骤。你真正想要做的第一件事就是聚集所有在第二个位置具有相同字符串的元组,所以你将会有一个像

  aggregate :: [(Int,String)]  - > [([Int],String)] 

因此,对于您的输入列表, ([1,2],a),([1],b),([1], c),([2],dd)]

>

 汇总物品= someFunc(地图(\(num,str) - >([num],str))items)

然后看看 foldr 。在提出有关 foldr 的后续问题之前,可能有数百个stackoverflow答案显示如何使用它,需要一些时间来弄清楚,否则它会关闭立即作为一个副本。

然后你需要一个函数来把这个表单的一个元组转换成一个 String 输出:

  prettyPrint ::([Int],String) - > String 
prettyPrint(nums,str)= str ++++ joinWithComma(map show nums)

你必须自己实现 joinWithComma 。然后,您需要计算此值并将其打印在聚合列表中的每个项目上, mapM _ putStrLn 所以你的 main 可能看起来像

  main :: IO()$ (2,a),(1,a),(1,b),(1,c),(2, dd)] 
mapM_(putStrLn. prettyPrint)(aggregate inputList)


I'm trying to get this list of tuples:

[(2,"a"), (1,"a"), (1,"b"), (1,"c"), (2,"dd")]

into this string output

a 1,2

b 1

c 1

dd 2

I assume I need to use the unzip and unlines functions. But I also saw some solutions using the show function which makes the integers strings. Any ideas?

解决方案

Break the problem down into steps. What you really want to do first is aggregate all the tuples that have the same string in the second position, so you'll have a function like

aggregate :: [(Int, String)] -> [([Int], String)]

So for your input list you would get the output

[([1, 2], "a"), ([1], "b"), ([1], "c"), ([2], "dd")]

Your hints are

aggregate items = someFunc (map (\(num, str) -> ([num], str)) items)

And take a look at foldr. Before you ask a follow up question about foldr, there are probably hundreds of stackoverflow answers showing how to use it already, take some time to figure it out or it'll get closed immediately as a duplicate.

Then you need a function to convert a single tuple of this form into a single String for outputting:

prettyPrint :: ([Int], String) -> String
prettyPrint (nums, str) = str ++ " " ++ joinWithComma (map show nums)

Where you'll have to implement joinWithComma yourself. Then you need to calculate this and print it for each item in your aggregated list, mapM_ and putStrLn would be preferred, so your main might look like

main :: IO ()
main = do
    let inputList = [(2,"a"), (1,"a"), (1,"b"), (1,"c"), (2,"dd")]
    mapM_ (putStrLn . prettyPrint) (aggregate inputList)

这篇关于Haskell:输出元组列表作为字符串输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆