【问题标题】:Arrange a list in Racket在 Racket 中排列列表
【发布时间】:2016-06-23 21:56:59
【问题描述】:

(排列'(0 1 1 2 3 3 4 5 6 6)) -> '(0 (1 1) 2 (3 3) 4 5 (6 6))

你好,我想做这个。 他们应该这样做,相同的下一个元素进入列表列表,其他元素进入普通列表。但我不知道如何使用 foldr 和 lambda 获取下一个元素。

我的代码:

(define (arrange l)
   (foldr (lambda (e1 e2 acc)
           (cons (if (= e1 e2)(list e1 e2) e1) acc))
         '()
         l l))

e2 不要看下一个元素,它们就像 e1。

【问题讨论】:

  • 输入总是排序的吗?或者可以是(1 2 1 3 2 4 1)((1 1 1) (2 2) 3 4)?编辑:此外,输出必须是相同的顺序,还是只是增加?
  • 输入已排序,输出必须相同。

标签: list lambda racket


【解决方案1】:

这是一种游程编码。一个典型的递归版本将是最简单的版本,我猜你有一个变量来保存最后一个元素和一个计数。

使用foldr 会稍微困难一些,但这是可行的,因为累加器中有已处理的元素,因此您可以与计算结果进行比较并更改它。

如果累加器为空,只需列出元素。

假设你正在处理一个 6 并且累加器有(6 ? ...),那么你需要将它设为((6 6) ? ...)

然后想象你正在处理一个 6 并且累加器有 ((6 6) ? ...) 那么你需要使它成为 ((6 6 6) ? ...)

当以上不匹配时,只会将元素添加到累加器。例如。元素是 5,你有 (? ...) 你让它 (5 ? ...)

【讨论】:

  • ok thx,lambda 不是那么重要,但我必须使用 foldr 来实现。 ...我不知道
  • @RedCubeMan 好吧,我不会为此使用foldr,但我的案例分析是准确的,因此您只需要编写代码即可。
【解决方案2】:

这是一个可行的解决方案:

(define (arrange lst)
  (foldr (lambda (item result)
           (cond
             [(empty? result) (cons item result)] ; On the first iteration, result will be empty, so we just add the item
             [(equal? item (first result)) (cons (list item (first result)) (rest result))] ; Does the current item match the last one? If so, put them both into a list
             [(and (list? (first result)) (member item (first result))) (cons (cons item (first result)) (rest result))] ; If the last item is a list, and our current item
                                                                                                                         ; is a member of it, cons them together
             [else (cons item result)])) ; If all else fails, just add the item
         empty lst))

请注意,由于只能使用foldr,因此这在某些涉及列表的输入上中断。

【讨论】:

    猜你喜欢
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    相关资源
    最近更新 更多