我无法找到一种有效的方法来从Haskell中的9个元素列表中挑选出4个元素的所有排列.python方式做同样的事情:
itertools.permutations(range(9+1),4)
Run Code Online (Sandbox Code Playgroud)
在Haskell中这样做不太有效:
nub . (map (take 4)) . permutations $ [1..9]
Run Code Online (Sandbox Code Playgroud)
我想找到类似的东西:
permutations 4 [1..9]
Run Code Online (Sandbox Code Playgroud)
小智 5
这是我的解决方案:
import Control.Arrow
select :: [a] -> [(a, [a])]
select [] = []
select (x:xs) = (x, xs) : map (second (x:)) (select xs)
perms :: Int -> [a] -> [[a]]
perms 0 _ = [[]]
perms n xs = do
(y, ys) <- select xs
fmap (y:) (perms (n - 1) ys)
Run Code Online (Sandbox Code Playgroud)
这是非常懒惰甚至适用于无限列表,虽然输出不是很有用.我没有打扰实现对角化或类似的东西.对于有限列表,它很好.