简体   繁体   中英

Racket/Scheme - Applying a function to each element in a list of lists

I am a physics major who is taking a math class with programming (I enrolled for the math), but I have never coded in any language before, so everything about Racket is completely new to me. The goal of the class so far is to take set-related functions and convert them to Racket programs. One of these functions is to take a list of lists and remove the first item of each element:

f({(0, 1, 0), (1, 0, 0), (1, 1, 1)...} = {(1, 0), (0, 0), (1, 1)...}

I've gotten this as a procedure so far:

(define (procA set)
  (cond
    ((null? set) '())
    ((rest (first set)))
    ((procA (rest set)))))

When I run the program, it comes back with the proper function applied, but only with the first element, like how

(procA '((0 1 0) (1 0 0) (1 1 1)))

comes back to be '(1 0). Is it some sort of "map" function, or something completely different? I thought the last line would take care of the rest of the list, but it didn't.

As @uselpa commented, it is the same as map rest . If you want to implement it, you need to use recursion and cons together the resulting list.

The most straight-forward approach, I think, is to use if to find the base case of the empty list:

(define (procB set)
  (if (null? set)
      '()
      (cons (rest (first set)) (procB (rest set)))))

If you want to use cond , the same can be written as

(define (procC set)
  (cond
    ((null? set) '())
    (else (cons (rest (first set)) (procC (rest set))))))

(where the else is not necessary in this case: if left out it will also be the "test expression without body" case described below. NB I only mean deleting the word else , not the expression following it.)

That is, the only thing missing from your code was the cons . In your code, the last statement (with the recursion) will never be executed, as cond chooses the first test-expression that is true (and (rest non-empty-list) is a "truthy" value. A similar example:

> (cond 
    ((= 1 2) 0)
    ((+ 3 4))
    ((+ 5 6)))
7

where the first test-expression is false, so it goes on to the second, which is true, and as it has no body, the result of the test expression becomes the result of the cond . The third test-expression is never executed.

(define (exclude list)
  (if (empty? list) '""
  (let ((r (rest list)) (f (rest (first list))))
   (~a f (exclude r))

)))
(exclude '( (3 4 5) ( 6 7 8) ( 9 10 11)))

;(4 5)(7 8)(10 11)

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