function like Mathematica's Tuples



Robert Dodier escribi?:
> This is interesting, but I don't think it works correctly,
> because subst makes serial substitutions where I think
> you want parallel substitution.
> e.g. tuples([3, 2, 1], 2) yields something incorrect, right?
>   

Hello,

Certainly, this gives an unwanted result. I don't know how robust and/or 
orthodox is the use of gensym, but it helps to circumvent this 
particular problem.


(%i1) tuples(lis, n) :=
   block(
     [ len_lis, aux_lis, aux_set, cart_prod],
     len_lis : length(lis),
     aux_lis : makelist(?gensym(),k,1,len_lis),
     aux_set : setify(aux_lis),
     cart_prod : apply(cartesian_product, makelist(aux_set,k,1,n)),
     subst(map("=", aux_lis, lis), listify(cart_prod)) ) $
(%i2) tuples([3, 2, 1], 2);
(%o2) [[3, 3], [3, 2], [3, 1], [2, 3], [2, 2], [2, 1], [1, 3], [1, 2], 
[1, 1]]

--
Mario