【问题标题】:how can i write a groupBy function for list elements in haskell?如何为haskell中的列表元素编写groupBy函数?
【发布时间】:2018-09-04 13:05:20
【问题描述】:

它的签名必须是这样的:

groupBy :: (a -> a -> Bool) -> [a] -> [[a]]

我的函数应该根据元素是否相等或其中是否存在严格单调递增的部分列表,将输入列表的元素分组到输出列表。

终止示例:

-- groupBy (==) groups the equal elements
groupBy (==) [0, 0, 1, 1, 2, 2] == [[0, 0], [1, 1], [2, 2]]
groupBy (==) [0, 1, 2] == [[0], [1], [2]]

-- groupBy (<) returns the strictly monotonous incrementing partlists
groupBy (<) [0, 1, 2, 1, 2, 3] == [[0,1,2],[1,2,3]]
groupBy (<) [3, 4, 5] == [[3, 4, 5]]

groupBy (>=) [3, 3, 1, 5] == [[3,3,1],[5]] --- monotonous decrementing

-- partlists, where the consecutive elements' difference is 1:
groupBy (\x y -> abs (x - y) == 1) [0, 1, 3, 4] == [[0, 1], [3, 4]]
groupBy (\x y -> abs (x - y) == 1) [1, 2, 3, 2, 1, 10, 11] == [[1,2,3,2,1],[10,11]]

提前感谢您的帮助:)

【问题讨论】:

  • 就写吧。你具体卡在哪里了?
  • 甚至不知道从哪里开始,但这是明天的任务:(
  • 网上有很多很好的Haskell教程;随时咨询某人以获取有关从哪里开始的一些想法,并在您编写的代码遇到具体问题时回来。至于你的另一半评论……我高中的乐队老师在他的门上贴了一张纸条:“你的计划不周不构成我的紧急情况。”。内化改变了我的生活,我希望你能像我一样发现它有帮助(尽管在你第一次糟糕的计划紧急情况下听到它确实很糟糕)。

标签: haskell functional-programming


【解决方案1】:

看看这里必须发生的比较。您提供了一个函数f :: a -&gt; a -&gt; Bool,只要它保持为真,它将对每个项目进行分组,换句话说:

groupBy (>=) [3, 3, 1, 5, 4]
                [3]
3 >= 3 = True   [3, 3]  -- add RHS value
3 >= 1 = True   [3, 3, 1]
1 >= 5 = False  -- new group!

                [5]
5 >= 4 = True   [5, 4]

这对我来说看起来像是递归。您的内部函数应该保留一个累加器,查看列表中的每个元素并决定 A)将其包含在当前累加器中或 B)返回累加器并根据 f 的结果开始一个新的累加器。

groupBy 定义为一些真正起作用的辅助函数的包装器可能会有所帮助。

groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy f (x:xs) = go f [x] xs
  where
  -- base case: no values left to check
  go _ acc       [] = [acc]

  -- recursive case
  go f acc@(y:_) (x:xs)
    | y `f` x   =  go f (x:acc) xs    -- add to current group
    | otherwise =  acc : go f [x] xs  -- start a new group

请注意,上面有一个细微的错误,我出于说明目的而留下了(也因为我先是这样写的,所以你也可以!)

【讨论】:

    猜你喜欢
    • 2019-03-14
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    相关资源
    最近更新 更多