在大学里,我们刚刚开始学习 Haskell。所以我对整个“函数式编程”世界真的很陌生......
我已经实现了一个函数,可以让您在列表中的每个点插入一个值。它已经在运行并且像这样工作。
-- Inserts a value of type a in each position of a list and returns a list of all those lists
insert :: a -> [a] -> [[a]]
我现在的任务是实现一个函数来计算给定列表的所有排列。所以我想我可以使用已经工作的
insert
-function 并这样做:perms :: [a] -> [[a]]
perms [] = [[]]
perms (x:xs) = insert x perms(xs)
但不幸的是它不起作用。我不确定,但我认为问题可能在于 insert
-function 创建一个列表列表,从而在递归时创建...的列表列表,这导致递归调用插入函数时出现问题,因为 x
不适合那些级联列表。有人可以帮我一下吗?非常感谢 :)
最佳答案
好的...我在 @chepner 的帮助下找到了解决方案.我的代码现在正在运行,看起来像这样:
perms :: [a] -> [[a]]
perms [] = [[]]
perms (x:xs) = insertEverywhere x (perms xs)
where insertEverywhere :: a -> [[a]] -> [[a]]
insertEverywhere e [[]] = [[e]]
insertEverywhere e [x] = (insert e x)
insertEverywhere e (l:ls) = (insert e l) ++ (insertEverywhere e ls)
关于list - 在haskell中获取列表的排列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64993140/