How to change the order of the contents of a list in racket?

删除回忆录丶 提交于 2020-06-27 16:57:17

问题


I'm a beginner in racket and am learning how lists work. I have to create a function that takes in a count variable and a list and produces the same list but with the first element cycled to the end of the list "count" number of times. My code works for even numbered lists, like calling the function 2 '(1 2 3 4), which results in a list '(3 4 1 2), but does not work for odd numbered lists, like calling 2 '(1 2 3), which should result in '(3 1 2)

(define (cycleN count aList)
  (cond
    [(empty? aList) '()]
    [(= count 0) aList]
    [(= count (length aList)) aList]
    [else (append (take-right aList count) (take aList count))]))

What am I missing?


回答1:


You should be take-right-ing (length aList) - count elements, not count.




回答2:


A recursive solution to this problem should make use of the base case, which is when count is zero: in this case, there is no rotation to be done and the input list should be returned as-is.

Otherwise, one rotation should be performed, and the count should be reduced.

With recursion the idea is to break the problem down into subproblems. There must be at least one base case which results in an immediate return of some result, and there must be a recursive step that reduces the problem. In this case, the count is reduced until the base case is reached. At each recursive step the first element of the list is appended to the end of the rest of the list, and the count is reduced by one until reaching the base case. When the base case is reached here, there is nothing to be done but return the result.

Note also that the below definition for cycle-n works when count is larger than the length of the input list (the result of (cycle-n 5 alist) for a list of length 4 should be the same as for (cycle-n 1 a-list)). The definition of cycleN, even in its "correct" form, fails for such cases.

(define (cycle-n count a-list)
  (cond
    [(zero? count) a-list]
    [else
     (cycle-n (- count 1)
              (append (rest a-list) (list (first a-list))))]))

Sample REPL interaction:

scratch.rkt> (cycle-n 1 '(1 2 3 4))
'(2 3 4 1)
scratch.rkt> (cycle-n 2 '(1 2 3 4))
'(3 4 1 2)
scratch.rkt> (cycle-n 3 '(1 2 3 4))
'(4 1 2 3)
scratch.rkt> (cycle-n 4 '(1 2 3 4))
'(1 2 3 4)
scratch.rkt> (cycle-n 5 '(1 2 3 4))
'(2 3 4 1)


来源:https://stackoverflow.com/questions/62239772/how-to-change-the-order-of-the-contents-of-a-list-in-racket

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!