'How to get the multiplication of two lists in Lisp or Scheme?

I think I'd have to dig into SICP later, but if it is two lists:

a b c d
1 2 3

Is there a standard way to get the multiplication of them in 2, 3 or 4 lines?

So the desired result is

a1 a2 a3 b1 b2 b3 ... d1 d2 d3

If we use any imperative language / method to do it, it is quite simple, but if we use Lisp / Scheme in a functional way (by declarative method), is there a standard method it is done?



Solution 1:[1]

DrRacket has cartesian-product:

(require racket/list)
(cartesian-product '(a b c d) '(1 2 3))

And you can rewrite your Javascript code this way (in Racket):

> (apply append (map (lambda (a) (map (lambda (b) (list a b))
                                 '(1 2 3)))
                '(a b c d)))

'((a 1) (a 2) (a 3) (b 1) (b 2) (b 3) (c 1) (c 2) (c 3) (d 1) (d 2) (d 3))

Or in Common Lisp:

CL-USER 1 > (apply #'append (mapcar (lambda (a) (mapcar (lambda (b) (list a b))
                                 '(1 2 3)))
                '(a b c d)))

((A 1) (A 2) (A 3) (B 1) (B 2) (B 3) (C 1) (C 2) (C 3) (D 1) (D 2) (D 3))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Martin Půda