Delete element from List in Scheme

后端 未结 3 2042
孤街浪徒
孤街浪徒 2021-01-23 04:21

I have list in this form

( (1 3) (2 2) (3 1) (4 5) (5 1)))

and I want to delete an item let\'s say (3 1)

So the result wi

3条回答
  •  醉话见心
    2021-01-23 05:01

    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)))
    ))
    

提交回复
热议问题