Question

I have a move procedure that applies a legal move to a chess piece on the board by passing a pair: (cons source dest) so (cons 1 2) takes a piece on position 1 from the board and moves it to position 2.

I'm trying to make a procedure that applies the same move it made before. I tried to do

(move (reverse move)) which would pass in (cons 2 1) thereby moving the piece back.

unfortunately, reverse doesnt work for pairs. I can't convert it to a list because that would have to change a lot of the code to accommodate for the null at the end.

Can anyone think of anything? I'm using MIT Scheme by the way.

Was it helpful?

Solution

You need to implement your own reverse-pair procedure for this, it can be as simple as this:

(define (reverse-pair p)
  (cons (cdr p) (car p)))

Or this, a bit fancier but less readable:

(define (reverse-pair p)
  `(,(cdr p) . ,(car p)))

Either way it works as intended:

(reverse-pair '(1 . 2))
=> '(2 . 1)

OTHER TIPS

If the reverse function doesn't work on pairs, write your own reverse-pair function then. I don't remember the scheme syntax for that but I think you already have the tools for that, since you would basically need to know how to read the two values from the pair (something you already do on your "move" function) and then how to build a new tuple based on that data.

I don't see why you think this would complicate things too much either. As far as the code outside the new function goes, it would look just the same as the original version you proposed using the "reverse" function.

If you limit yourself to pairs of `(a . b) then it's pretty easy to flip them. Something as simple as

(define reverse-pair
  (lambda (p)
    (cons (cdr p) (car p))))

Will do it. From your context I gather that your not going to be in the position where you have '(1 2 3 4 . 5) and need to reverse that so you should be fine with the one above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top