Alex Silkovsky
Alex Silkovsky

Reputation: 561

Reverse list on top level without 'appent' or 'list'

I made some function that can reverse simple lists, like (q w e r t y)
By the task it should correctly process: empty lists, lists, pairs, improper lists.
But now it fails on improper lists, like (q w e r t . y) or pairs.
How to process this situations?

My code:

(define myInverse2
  (lambda (original result)
    (
     cond ((null? original) 
           result  )
          (#t 
           (myInverse2 (cdr original) (cons (car original) result))  )
) ) )

And dr Racket output:

enter image description here

Upvotes: 0

Views: 128

Answers (1)

coredump
coredump

Reputation: 38967

Your code fails because when original is not null?, you assume you can take the cdr of it, which is not always guaranteed. You could fix your code to distinguish between cons? values and other values.

But first, ask yourself if this is necessary and what would be the reverse of some of your inputs. The reverse of a simple pair (x . y) is (y . x).

But what about the reverse of (q w e r t . y)? I would expect reverse be its own inverse function (i.e. involution), so that you always have:

(equal? x (reverse (reverse x)))

... and if the reverse of the above is (y t r e w q), then you lose this property. Or, you could chose to have the result be (y t r e w . q), which, when reversed, gives you your result back. That is why you first have to chose what is the meaning of your function. Then, if the above approach is the one you want to take, then change should be easy; e.g. add a case in your cond which matches (cons? original).

Upvotes: 2

Related Questions