This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

Get a column as a list

7 posts · 1929 views

Hi,

I'm trying to implement a simple sudoku solver and came up with this problem:

Consider this:
(defvar board '(
(1 0 0 0 0 7 4 0 0)
(9 0 6 4 0 0 0 0 0)
(0 5 0 8 3 0 0 0 0)
(3 6 0 0 0 0 0 0 5)
(0 0 0 0 2 0 0 0 0)
(5 0 8 0 0 0 0 1 4)
(0 0 0 0 7 3 0 9 0)
(0 0 0 0 0 8 7 0 6)
(0 0 5 9 0 0 0 0 1)))
How can I get a list with the contents of the nth column?

Re: Get a column as a list

It would be better to represent the board as an array, since random access to contents is required. Then you can just manipulate the contents with indexes. Or perhaps using something like grid structured data library.

Re: Get a column as a list

Thanks for the reply.

I'll give it a try.

Re: Get a column as a list

MrCode wrote:How can I get a list with the contents of the nth column?
With a cunning combination of mapcar and nth :)

Re: Get a column as a list

To pack a question in an answer:
(defun curry-l (fun &rest curried)
  "Curry to the left; add arguments to the start of the function.
Note: uses apply.. Hope it will optimize."
  (lambda (&rest args)
    (apply fun (append curried args))))

(defun nth-column (table-list n)
  (mapcar (curry-l #'nth n) table-list))
Does that curry optimize? Why isn't it in CL?

Re: Get a column as a list

Jasper wrote:To pack a question in an answer:
(defun curry-l (fun &rest curried)
  "Curry to the left; add arguments to the start of the function.
Note: uses apply.. Hope it will optimize."
  (lambda (&rest args)
    (apply fun (append curried args))))

(defun nth-column (table-list n)
  (mapcar (curry-l #'nth n) table-list))
Does that curry optimize? Why isn't it in CL?
(1) No, it does not optimize, and (2) who knows? I agree with you, it is so pretty, it should be in the standard ;)

Curry can be optimized if a proper compiler macro is written. For instance, see alexandria's code, it has compiler macros for curry, rcurry, compose and others.

Re: Get a column as a list

Thanks, solved! Now I came up with another problem. Consider this function:
(defun list-intersection (l1 l2)
  (cond
     ((null l1) nil)
     ((member (first l1) l2)  (cons (first l1) (list-intersection (rest l1) l2)))
     (t (list-intersection (rest l1) l2))))
It works fine with: (A B C) and (H F A) -> (A), but I wanted it to work with: ((A B C) (D F)) and ((A J K) (D F)) -> nil.