列表的排列 - 哈斯克尔 [英] Permutations of a list - Haskell

查看:78
本文介绍了列表的排列 - 哈斯克尔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让所有可能的组合与2列表。这里有一个函数可以做到这一点:

I want to make all possible combinations of subgroups with 2 lists. Here is a function that does just this:

getCombinations :: [a] -> [[a]]
getCombinations na = do
    a <- na
    b <- na
    [[a,b]]

如果您将abc传递给此函数,它将返回:

If you pass "abc" to this function, it returns this:

["aa","ab","ac","ba","bb","bc","ca","cb","cc"]

对相同方法的简单修改可以返回3个列表的组合,而不是两个。

A simple modification of the same method could return combinations of 3 lists instead of two.

getCombinations :: [a] -> [[a]]
getCombinations na = do
    a <- na
    b <- na
    c <- na
    [[a,b,c]]

传递abc作为参数的结果:

Result of passing "abc" as an argument:

["aaa","aab","aac","aba","abb","abc","aca","acb","acc",
"baa","bab","bac","bba","bbb","bbc","bca","bcb","bcc",
"caa","cab","cac","cba","cbb","cbc","cca","ccb","ccc"]

使其扩展到任意数量的列表最简单的方法是什么?以下是类型声明的样子:

What's the simplest way to make it scale to an arbitrary number of lists? Here is what the type declaration should look like:

getCombinations :: Int -> [a] -> [[a]]


推荐答案

HREF = http://hackage.haskell.org/package/containers-0.5.5.1/docs/Data-Sequence.html#v:replicateM> replicateM

What you want is replicateM:

replicateM :: Int -> m a -> m [a]

定义非常简单:

The definition is as simple as:

replicateM n = sequence . replicate n

,所以它是序列 monad在这里做了真正的工作。

so it's sequence on the list monad that's doing the real work here.

这篇关于列表的排列 - 哈斯克尔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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