【问题标题】:Getting the permutation of a list in haskell?在haskell中获取列表的排列?
【发布时间】:2021-03-07 15:03:42
【问题描述】:

在大学里,我们刚刚开始学习 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-函数创建了一个列表列表,从而在递归时创建了一个列表列表,这会在递归调用插入函数时导致问题,因为x 不适合那些级联列表。 有人可以帮我解决这个问题吗?非常感谢:)

【问题讨论】:

  • 由于perms xs返回一个列表列表,您一次只能在其中一个列表上调用insert x,然后合并结果。考虑利用列表 monad,perms xs >>= insert x
  • insert x perms(xs) 使用三个参数调用insertxpermsxs。括号是多余的。如果您想确保使用xs 调用perms,请改用(perms xs)

标签: list haskell functional-programming permutation


【解决方案1】:

好的...我在@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)

【讨论】:

    猜你喜欢
    • 2017-02-27
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    相关资源
    最近更新 更多