Search code examples
functional-programmingschemeartificial-intelligencemit-scheme

move for a chess game


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.


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)