获取Haskell中列表的所有排列 [英] Get all permutations of a list in Haskell

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

问题描述

我试图从头开始,而不使用标准库之外的库。下面是我的代码:

I'm trying to do this from scratch, without the use of a library outside the standard lib. Heres my code:

permutations :: [a] -> [[a]]
permutations (x:xs) = [x] : permutations' xs
    where permutations' (x:xs) = (:) <$> [x] <*> split xs
            split l = [[x] | x <- l]

问题是这只会产生一个非确定性计算的分支。理想情况下,我想要

The problem is that this only produces one fork of the non-deterministic computation. Ideally I'd want

(:) <$> [x] <*> ((:) <$> [x] <*> ((:) <$> [x] <*> ((:) <$> [x] <*> xs)))

但我找不到干净利落的方法。我想要的结果是这样的:

But I can't find a way to do this cleanly. My desired result is something like this:

permutations "abc" -> ["abc", "acb", "bac", "bca", "cab", "cba"]

我该如何做到这一点?

推荐答案

也许你应该使用现有的代码:

Maybe you should use existing code:

import Data.List
permutations [1,2,3,4]

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

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