简体   繁体   English

在Haskell的嵌套列表的每个排列中添加一个元素

[英]Adding an element to each permutation of a nested list in Haskell

Let's say I have a nested list 假设我有一个嵌套列表

[1,2,3]

When I use the Data.List module to permutate this list, the result is the following: 当我使用Data.List模块排列此列表时,结果如下:

> permutations [1,2,3]
=> [[1,2,3],[2,1,3],[3,2,1],[2,3,1],[3,1,2],[1,3,2]]

But I want it such that, I'm concatenating a 0 at the end of each tail. 但是我想要这样,我在每条尾巴的末尾连接一个0。 Example: 例:

=> [[1,2,3,0],[2,1,3,0],[3,2,1,0],[2,3,1,0],[3,1,2,0],[1,3,2,0]]

I'm thinking that the only way of doing this is modifying the source code of permutations as a different function but I'm not sure how to incorporate the concatenation into it. 我认为这样做的唯一方法是将置换的源代码修改为另一个函数,但是我不确定如何将串联合并到其中。 This would be the source: 这将是来源:

import Data.List

permutations            :: [a] -> [[a]]
permutations xs0        =  xs0 : perms xs0 []
  where
    perms []     _  = []
    perms (t:ts) is = foldr interleave (perms ts (t:is)) (permutations is)
      where interleave    xs     r = let (_,zs) = interleave' id xs r in zs
            interleave' _ []     r = (ts, r)
            interleave' f (y:ys) r = let (us,zs) = interleave' (f . (y:)) ys r
                                     in  (y:us, f (t:y:us) : zs)

If there's a better way to approach this by using the permutation function without permutating the zero, it would be much appreciated. 如果有一种更好的方法来使用置换函数而不置换零,那么将不胜感激。

Although it might be more efficient to do this at the permutation level, we can simply first do all the permutations, and then post process this, with a map , so: 尽管在排列级别执行此操作可能会更有效,但是我们可以简单地首先执行所有排列,然后使用map进行后期处理 ,因此:

import Data.List(permutations)

our_perm :: Num a => [a] -> [[a]]
our_perm = map (++[0]) . permutations

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM