We will write a procedure every-nth that accepts two arguments: num is an integer and list-of-sents is a list of a certain number of lists. every-nth selects the num-th elements from each list in list-of-sents and returns the list of selected elements. Assume that all lists in listof-sents have more than num elements(piease use racket))
时间: 2023-11-22 21:55:46 浏览: 67
Here's a possible implementation of the `every-nth` procedure in Racket:
```racket
(define (every-nth num list-of-sents)
(define (helper lst acc)
(if (null? lst)
(reverse acc)
(helper (cdr lst) (cons (list-ref (car lst) (sub1 num)) acc))))
(helper list-of-sents '()))
```
The `every-nth` procedure takes two arguments: `num`, an integer representing the position of the element to select from each list, and `list-of-sents`, a list of lists. The procedure uses a helper function `helper` that takes two arguments: `lst`, the remaining lists to process, and `acc`, the accumulated list of selected elements.
The helper function uses recursion to process each list in `list-of-sents`. At each step, it selects the `num`-th element from the first list in `lst` using `list-ref`, adds it to the accumulator `acc` using `cons`, and recurses on the rest of the list using `cdr`. When the list is empty, the helper function returns the reversed accumulator, since elements were added to it in reverse order.
Finally, the `every-nth` procedure calls the helper function with `list-of-sents` and an empty accumulator to start the recursion. The selected elements are returned as a list.
阅读全文