[英]Arrange a list in Racket
(排列'(0 1 1 2 3 3 4 5 6 6))->'(0(1 1)2(3 3)4 5(6 6))
您好,我想做这个。 他们应该这样做,相同的下一个元素进入列表列表,其他元素进入普通列表。 但是我不知道如何使用文件夹和lambda来处理下一个元素。
我的代码:
(define (arrange l)
(foldr (lambda (e1 e2 acc)
(cons (if (= e1 e2)(list e1 e2) e1) acc))
'()
l l))
e2不要看下一个元素,它们就像e1。
这是一种游程长度编码。 我猜想,典型的递归版本将是最简单的版本,在该变量中,变量包含最后一个元素和一个计数。
使用foldr
会稍微困难一些,但是它是可行的,因为累加器中已经处理了元素,因此可以与计算结果进行比较并对其进行更改。
如果累加器为空,只需列出该元素。
因此,假设您正在处理6,而累加器具有(6 ? ...)
,那么您需要使其成为((6 6) ? ...)
。
然后想象您正在处理一个6并且累加器具有((6 6) ? ...)
那么您需要使其成为((6 6 6) ? ...)
如果以上都不匹配,则将元素限制在累加器中。 例如。 元素是5,而您拥有(? ...)
,就等于(5 ? ...)
这是一个可行的解决方案:
(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
,因此这在涉及列表的某些输入上会中断。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.