我有一个字符串列表列表,我需要使用句点将它们格式化为三角形,这样每个列表都在自己的行上,并且每个列表的字符串至少由一个句点分隔。此外,每个字符的上方和下方都必须有点。这可能最好通过示例来解释:
> dots [["test"], ["hello", "world"], ["some", "random", "words"], ["even", "more", "random", "words"]]
应该返回
............test.....................
.......hello.......world.............
...some......random......words.......
not....really......random.....anymore
最后,它应该使用尽可能少的句点,即将每个单词填充到最大单词长度的方法太浪费了;那就是上面的例子不应该返回
.....................test........................
..............hello.........world................
.......some..........random........words.........
not...........really........random........anymore
我可以轻松编写一个函数,将句点放在两边使其变成三角形,我的问题是单词之间的句点。
我有一个只要单词长度为 1 的函数就可以工作,这显然对这项任务毫无用处。尽管如此,我的函数 dots
:
dots :: [[String]] -> [[String]]
dots xss = map dots' xss
where dots' (x:[]) = [x]
dots' (x:xs) = [x] ++ ["."] ++ dots' xs
这是一个家庭作业,所以最好有提示,但我已经尝试了几个小时没有运气。
最佳答案
首先你需要一个函数,它将占位符添加到这样的列表中:
addPlaceholders [ ["test"]
, ["hello", "world"]
, ["some", "random", "words"]
, ["not", "really", "random", "anymore"]
]
==> [ ["" , "" , "" , "test" , "" , "" , "" ]
, ["" , "" , "hello" , "" , "world" , "" , "" ]
, ["" , "some", "" , "random", "" , "words", "" ]
, ["not", "" , "really", "" , "random", "" , "anymore"]
]
现在您需要用点填充这些 ""
。所以你可以编写一个辅助函数,将点添加到列表中:
addDots ["test", "", "random", ""]
==> ["test..","......","random","......"]
然后 fill
就是简单的
fill = transpose . map addDots . transpose
而你的功能只是
triangle = map concat . fill . addPlaceholders
https://stackoverflow.com/questions/27575892/