Thursday, August 12, 2010

Cartesian Product in Lisp

One of the things I do quite often is calculate the Cartesian product of two lists.  Here is my solution to problem in Lisp.

Usage Example:
> (product '() '())
NIL
> (product '(1 2) '(1 2 3))
((1 1) (1 2) (1 3) (2 1) (2 2) (2 3))


Implementation:
(defun product (list1 list2)
    (let (templist '())
        ;;iterate through the first list
        (dolist (item1 list1)
            ;;iterate through the second list
            (dolist (item2 list2)
                ;;create a list from the current items and push it onto the temporary list;;
                (push (list item1 item2) templist)
            )
        )
        ;;reverse the temporary list to display it correctly

        (nreverse templist)
    )
)

No comments:

Post a Comment