Cartesian product in Scheme

John Retallack picture John Retallack · Mar 21, 2010 · Viewed 8.6k times · Source

I've been trying to do a function that returns the Cartesian Product of n sets,in Dr Scheme,the sets are given as a list of lists,I've been stuck at this all day,I would like a few guidelines as where to start.

----LATER EDIT -----

Here is the solution I came up with,I'm sure that it's not by far the most efficent or neat but I'm only studing Scheme for 3 weeks so be easy on me.

Answer

Mark H Weaver picture Mark H Weaver · Dec 15, 2013

Here's a concise implementation that is also designed to minimize the size of the resulting structure in memory, by sharing the tails of the component lists. It uses SRFI-1.

(define (cartesian-product . lists)
  (fold-right (lambda (xs ys)
                (append-map (lambda (x)
                              (map (lambda (y)
                                     (cons x y))
                                   ys))
                            xs))
              '(())
              lists))