How to delete an element from a list in scheme

前端 未结 5 1833
渐次进展
渐次进展 2020-12-19 18:26

how to delete an element from a list ex:- list=[1 2 3 4]

I have come up with some code.I think I got wrong somewhere.

 (define delete item
   (lambda         


        
5条回答
  •  失恋的感觉
    2020-12-19 18:55

    1) if consider the input list may be a simple list, or you just want to delete the item in the top-level of a nested list for example:

    delete 2 from (1 2 3 4) will return (1 2 3)
    delete 2 from (1 2 3 (2 3) 3 2 4) will return (1 3 (2 3) 3 4)
    

    as we can see the 2nd example above, it just delete the item in the top-level of the nested list, within the inner list, we doesn't change it.

    this code should be:

    (define (deleteitem list1 item) 
    ( cond
        ((null? list1) ’())
        ((equal? (car list1) item) (deleteItem (cdr list1) item)) 
        (else (cons (car list1) (deleteitem (cdr list1) item)))
    ))
    

    2) if consider the input list may be a nested list

    for example:

    input list: (1 2 3 (3 2 (2 4 (2 5 6) 2 5 6) 2 4) 2 3 (2 3 4))
    

    and delete the element 2 in the input list

    the output list should be: (1 3 (3 (3 (5 6) 5 6) 4) 3 (3 4))
    

    and the code should be:

    (define (delete2 list1 item) 
        ( cond
        ((null? list1) '())
        ((pair? (car list1)) (con (delete2 (car list1) item) (delete2 (cdr list1) item)))
        ((equal? (car list1) item) (delete2 (cdr list1) item)) 
        (else (cons (car list1) (delete2 (cdr list1) item)))
    ))
    

提交回复
热议问题