简体   繁体   中英

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

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?

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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