S.J.
S.J.

Reputation: 27

Mapcar and Lambda, an undeclared variable error in LISP

I am trying to get the hang of using mapcar and lambda in LISP. Below, I have a non-working line of code, in which I’m trying to use them. I get an error, that c is an undeclared free variable.

Where am I going wrong? Below is the line of code that fails. Then, my second block is working code, though it is bulkier.

(mapcar #'(lambda (c) (member *opponent* (nth c board))) c)

(list (find-empty-position board *corners*)
      "Squeeze Play!  3rd move.")

Working code:

 (member *opponent*
 (list
  (nth (first *corners*) board)
  (nth (second *corners*) board)
  (nth (third *corners*) board)
  (nth (fourth *corners*) board)))

(list (find-empty-position board *corners*)
      "Squeeze Play!  3rd move.")

Upvotes: 0

Views: 110

Answers (1)

Barmar
Barmar

Reputation: 780843

To use mapcar you have to have a list to map over. It looks like you want to iterate over the elements of *corners*.

(mapcar #'(lambda (c) (member *opponent* (nth c board)))
        *corners*)

But to be equivalent to the second code, you shouldn't call member inside the loop, it should be called on the result of mapping:

(member *opponent*
        (mapcar #'(lambda (c) (nth c board)) *corners*))

Upvotes: 3

Related Questions