The goal of this function is to generate the cartesian product of 2 list. For example
(combo (list 1 2 3) (list 4 5)) => (1 4) (1 5) (2 4) (2 5) (3 4) (3 5)
(defun combo (l1 l2) (let ( (res (list)) ) (dolist (elem1 l1 res) (dolist (elem2 l2 res) (setq res (append res (list(list elem1 elem2)))) ) ) )
)
How could be implemented recursively?
A simple recursive implementation would be to use two helper functions; one to traverse through
L1
(%COMBO
in the code below), calling another function to pair an element with each element fromL2
(%PRODUCT
):The iterative approach is both simpler and more efficient though. Instead of using
APPEND
in a loop, you should just reverse the list at the end.You could also just use the
MAP-PRODUCT
function from Alexandria:It seems ideal for Prolog, though data has to be put differently: