简体   繁体   English

安排球拍中的清单

[英]Arrange a list in Racket

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

Hello, I want to make this. 您好,我想做这个。 They should do, the same next element come in a list of list the other elements go in a normal list. 他们应该这样做,相同的下一个元素进入列表列表,其他元素进入普通列表。 But i have no idea how i can take the next element with foldr and lambda. 但是我不知道如何使用文件夹和lambda来处理下一个元素。

my Code: 我的代码:

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

e2 dont look at the next element, they are like e1. e2不要看下一个元素,它们就像e1。

This is a kind of run length encoding. 这是一种游程长度编码。 A typical recursive version would be the simplest one I guess where you have a variable holding last element and a count. 我猜想,典型的递归版本将是最简单的版本,在该变量中,变量包含最后一个元素和一个计数。

Using foldr would be slightly more difficult, but it is doable since you have the already processed elements in the accumulator so you can compare with a computed result and alter it. 使用foldr会稍微困难一些,但是它是可行的,因为累加器中已经处理了元素,因此可以与计算结果进行比较并对其进行更改。

If the accumulator is empty just make a list of the element. 如果累加器为空,只需列出该元素。

So imagine you are processing a 6 and the accumulator has (6 ? ...) , then you need to make it ((6 6) ? ...) . 因此,假设您正在处理6,而累加器具有(6 ? ...) ,那么您需要使其成为((6 6) ? ...)

Then imagine you are processing a 6 and the accumulator has ((6 6) ? ...) then you need to make it ((6 6 6) ? ...) 然后想象您正在处理一个6并且累加器具有((6 6) ? ...)那么您需要使其成为((6 6 6) ? ...)

When non of the above matches just cons the element to the accumulator. 如果以上都不匹配,则将元素限制在累加器中。 eg. 例如。 element is 5 and you have (? ...) you make it (5 ? ...) 元素是5,而您拥有(? ...) ,就等于(5 ? ...)

Here is a working solution: 这是一个可行的解决方案:

(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))

Please note that this will break on some input involving lists, due to only being able to use foldr . 请注意,由于只能使用foldr ,因此这在涉及列表的某些输入上中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM