从球拍列表中递归删除元素

时间:2020-10-14 19:55:15

标签: racket

我需要从Racket列表中深度删除元素。这意味着在任何子列表中,我也需要从那里删除该元素。我收到一条我不太明白的错误消息。这是我的代码:

(define (my_delete atm lst);define function and set up parameters
  (define (rm x ls);define remove function
    (if (null? ls);check to see whether the list is null
      '();return a null list
      (if (eqv? x (car ls));check to see whether x is equal to the current element in the list
          (rm x (cdr ls));recursively call the function
          (cons (car ls)
                (rm x (cdr ls))))));recursively call the function
  (define (my-map f lst2);define my-map function and set up parameters
  (cond
   [(empty? lst2) empty];if the list is empty return an empty list
   [else (cons (f (first lst2) lst);apply the mapAction function to the element
               (my-map f (rest lst2)))]));recursively call the function
  (define (mapAction atm2 lst2);define mapAction function and set up parameters
    (if (list? atm2));check to see whether the element is a list
        (my_delete atm atm2);recursively call the function
        (if (eq? atm atm2));check to see whether the elements are equal
        (rm atm2 lst2);remove the element if they are equal
    
  )
  (my-map mapAction list)
)

这是我的错误消息:

if: bad syntax in: (if (list? atm2))

请帮忙!

1 个答案:

答案 0 :(得分:0)

我想知道当(if (list? atm2))为真或假时(list? atm2)应该做什么。通常您会拥有(if (list? atm2) expression-if-true expreession-if-false)。同样在DrRacket中,当我按下CTRL + i时,它会根据这些括号错误来格式化代码。我将为您注释mapAction

(define (mapAction atm2 lst2) ; define mapAction function and set up parameters
  (if (list? atm2))           ; check to see whether the element is a list don't do ANYTHING either way
  (my_delete atm atm2)        ; Then always recursively call the function 
  (if (eq? atm atm2))         ; Then ignore the result and check to see whether the elements are equal and dont do ANYTHING wither way
  (rm atm2 lst2))             ; Than always remove the element unconditionally (also result of procedure)

这是完全不同的东西:

(define (mapAction atm2 lst2) ; define mapAction function and set up parameters
  (if (list? atm2)            ; check to see whether the element is a list
      (my_delete atm atm2)    ; recursively call the function
      (if (eq? atm atm2)      ; check to see whether the elements are equal
          (rm atm2 lst2)      ; remove the element if they are equal
          'what-to-do-else))) ; if has 3 parts. THis is executed when atm and atm2 are not the same thing

cond看起来更好,因为它在else分支中嵌套了术语,就像elseif一样。

相关问题