gpt4 book ai didi

haskell - 列表的排列 - Haskell

转载 作者:行者123 更新时间:2023-12-03 14:32:28 26 4
gpt4 key购买 nike

我想用 2 个列表制作所有可能的子组组合。这是一个执行此操作的函数:

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

如果你将“abc”传递给这个函数,它会返回:
["aa","ab","ac","ba","bb","bc","ca","cb","cc"]

对相同方法的简单修改可以返回 3 个列表的组合,而不是两个。
getCombinations :: [a] -> [[a]]
getCombinations na = do
a <- na
b <- na
c <- na
[[a,b,c]]

将“abc”作为参数传递的结果:
["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"]

使它扩展到任意数量的列表的最简单方法是什么?下面是类型声明的样子:
getCombinations :: Int -> [a] -> [[a]]

最佳答案

你要的是 replicateM :

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

定义很简单:
replicateM n = sequence . replicate n

所以它是 sequence在这里做真正工作的单子(monad)名单上。

关于haskell - 列表的排列 - Haskell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8779765/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com