Cartesian product of two or more lists: Difference between revisions

Added scheme
(Added Crystal implementation)
(Added scheme)
Line 3,477:
{{out}}
<pre>{}</pre>
 
=={{header|Scheme}}==
<lang scheme>
(define cartesian-product (lambda (xs ys)
(if (or (zero? (length xs)) (zero? (length ys)))
'()
(fold append (map (\ (x) (map (\ (y) (list x y)) ys)) xs)))))
 
(define nary-cartesian-product (\ (ls)
(if (fold (\ (a b) (or a b)) (map (compose zero? length) ls))
'()
(map flatten (fold cartesian-product ls)))))
 
> (cartesian-product '(1 2) '(3 4))
((1 3) (1 4) (2 3) (2 4))
> (cartesian-product '(3 4) '(1 2))
((3 1) (3 2) (4 1) (4 2))
> (cartesian-product '(1 2) '())
()
> (cartesian-product '() '(1 2))
()
> (nary-cartesian-product '((1 2)(a b)(x y)))
((1 a x) (1 a y) (1 b x) (1 b y) (2 a x) (2 a y) (2 b x) (2 b y))
</lang>
 
=={{header|Sidef}}==