形成Haskell排列的输出

时间:2018-01-24 19:29:21

标签: string haskell concatenation

我的.hs文件中有此列表

listofstrings= ["string1", "string2", "string3", "string4"]

我正在使用

调用ghci中的文件
load permutations.hs

使用此命令

permutations listofstrings

我得到了

[["string1","string2","string3","string4"],["string2","string1","string3","string4"],["string3","string2","string1","string4"],["string2","string3","string1","string4"],["string3","string1","string2","string4"],["string1","string3","string2","string4"],["string4","string3","string2","string1"],["string3","string4","string2","string1"],["string3","string2","string4","string1"],["string4","string2","string3","string1"],["string2","string4","string3","string1"],["string2","string3","string4","string1"],["string4","string1","string2","string3"],["string1","string4","string2","string3"],["string1","string2","string4","string3"],["string4","string2","string1","string3"],["string2","string4","string1","string3"],["string2","string1","string4","string3"],["string4","string1","string3","string2"],["string1","string4","string3","string2"],["string1","string3","string4","string2"],["string4","string3","string1","string2"],["string3","string4","string1","string2"],["string3","string1","string4","string2"]]

我如何获得每个组合的列表,其中包含换行符,没有逗号,“,[],空格和其他符号?

所以看起来应该是这样的

string1string2string3string4
string2string1string3string4
string3string2string1string4
string2string3string1string4
string3string1string2string4
string1string3string2string4
string4string3string2string1
string3string4string2string1
string3string2string4string1
string4string2string3string1
string2string4string3string1
string2string3string4string1
string4string1string2string3

2 个答案:

答案 0 :(得分:4)

您可以使用.have_inner_item { display: flex; flex-direction: column; 加入每个子列表的字符串,然后您可以与concat一起加入行:

unlines

Here's an example

答案 1 :(得分:-2)

您可以使用map获取新的字符串列表,但每行都附加换行符:

listsWithNewLines = map (++ ["\n"]) $ permutations listofstrings

然后使用mapM_打印出来:

mapM_ putStr (concat listsWithNewLines)

为什么mapM_?因为您要执行不返回IO的{​​{1}}操作,换句话说,您想在() monad中进行一些计算。

让我们回顾IO的类型:

mapM_

我们的计算结果为mapM_ :: Monad m => (a -> m b) -> [a] -> m () ,具有以下类型:

putStr

因为我们想要一个字符串列表作为putStr :: String -> IO () 的第二个参数,我们需要用新行来拼合我们的字符串列表:mapM_

因此,我们最终得到以下类型:

concat listWithNewLines

这是(String -> IO ()) -> [String] -> IO () 的类型,但mapM_a = Stringb = ()