|
|
|
|
|
by kragen
4711 days ago
|
|
Well, you could do it this way: (defn cross2 [xs ys]
(cond (or (and (sequential? xs) (empty? xs)) (empty? ys)) '()
(not (sequential? xs)) (cons (list xs (first ys)) (cross2 xs (rest ys)))
true (concat (cross2 (first xs) ys) (cross2 (rest xs) ys))))
which is pretty much exactly homologous, allowing for the detail that you can't ask if an atom is empty? in Clojure, cond (Arc-like) takes alternating conditions and consequents rather than condition-consequent pairs, and the spellings of the list operations no longer refer to IBM 709 machine instructions. Also, it works on any kind of sequences, not just lists, with of course a punishing performance overhead on sequences whose `rest` operation is slow.But I would argue that this interface is poorly designed, since you can say (cross2 '(a b c) '(1 2 3)) or (cross2 'a '(1 2 3)) but not (cross2 '(a b c) '1), and worse, (cross2 '(a (b c) d) '(1 2 3)) implicitly flattens the (b c) into individual items, which is probably a latent bug rather than desired behavior. So I would argue for writing it in this form instead: (defn sc [x ys] ; scalar cross
(if (empty? ys) '()
(cons (list x (first ys)) (sc x (rest ys)))))
(defn cross [xs ys]
(if (or (empty? xs) (empty? ys)) '()
(concat (sc (first xs) ys) (cross (rest xs) ys))))
which avoids those irregularities and makes the code easier to understand by removing misleading false symmetries.Except really, if this isn't a homework problem, I think you should write it like this in any of these three Lisps: (defn cross [xs ys]
(map (fn [x] (map (fn [y] (list x y)) ys)) xs))
|
|
One more subtle thing: your solution produces (((a 1) (a 2)) ((b 1) (b 2)) ((c 1) (c 2))) while the contract was to produce "list of all possible pairs".