在Haskell中列出9个所有可能的4个选项 [英] List all possible 4 chooses from 9 in Haskell

查看:173
本文介绍了在Haskell中列出9个所有可能的4个选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法找到一种从Haskell中的9个元素列表中挑选出4个元素的有效方法。
python-way做同样的事情:

  itertools.permutations(range(9 + 1),4 )

在Haskell中不是很有效的方法:

  nub。 (地图(拿4))。 permutations $ [1..9] 

我想找到如下所示的内容:

  permutations 4 [1..9] 


<

  import Control.Arrow 

select :: [a] - > [(a,[a])]
选择[] = []
选择(x:xs)=(x,xs):地图(第二个(x :))(选择xs)

perms :: Int - > [a] - > [[a]]
perm 0 _ = [[]]
perms n xs = do
(y,ys)< - 选择xs
fmap(y :)( perm(n-1)ys)

它非常懒惰,甚至适用于无限列表,尽管输出没有什么用处。我没有打扰实现对角化或类似的东西。对于有限的列表,它很好。


I'm not able to find an effective way to pick out all permutations of 4 elements from a list of 9 elements in Haskell. The python-way to do the same thing:

itertools.permutations(range(9+1),4)

An not so effective way to do it in Haskell:

nub . (map (take 4)) . permutations $ [1..9]

I would like to find something like:

permutations 4 [1..9]

解决方案

Here is my solution:

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)

It's very lazy and even works for infinite lists, although the output there is not very useful. I didn't bother implementing diagonalization or something like that. For finite lists it's fine.

这篇关于在Haskell中列出9个所有可能的4个选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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