[racket] Generating Tuples from List

From: Neil Toronto (neil.toronto at gmail.com)
Date: Wed Feb 29 23:09:43 EST 2012

So... that's exactly what you'd do if you didn't have for* macros. Using 
for* macros and turning the false branch into a helper function results 
in this:

;; product : (listof a) (listof b) -> (listof (cons a b))
(define (product lst1 lst2)
   (for*/list ([x  (in-list lst1)]
               [y  (in-list lst2)])
     (cons x y)))

;; tuples : (listof a) natural -> (listof (listof a))
(define (tuples lst n)
   (cond [(= n 0)  (list empty)]
         [else     (product lst (tuples lst (- n 1)))]))


You'd want error checking or a contract on `tuples', of course.

Neil ⊥

On 02/29/2012 08:32 PM, Adam Shaw wrote:
> (define (tuples xs n)
> (if (<= n 0)
> (list empty)
> (foldr append empty (map (λ (t) (map (λ (x) (cons x t)) xs)) (tuples xs
> (sub1 n))))))
>
>
> On Feb 29, 2012, at 8:52 PM, Ashok Bakthavathsalam wrote:
>
>> Again, trying to mimic something available in Mathematica (Tuples -
>> Wolfram Mathematica 8 Documentation http://bit.ly/AgsIym).
>> How can this be accomplished in Racket? Here's an example from the
>> Mathematica documentation.
>> All possible 3-tuples of and :
>> In[1]:= <http://reference.wolfram.com/mathematica/ref/Tuples.html>	
>> Click for copyable input
>> <http://reference.wolfram.com/mathematica/ref/Tuples.html>
>>
>> Out[1]=	
>>
>>
>> No, this is not homework. So, would appreciate code if available.
>>
>> Thanks,
>>
>> % ashok
>>
>> ____________________
>> Racket Users list:
>> http://lists.racket-lang.org/users
>
>
>
> ____________________
>    Racket Users list:
>    http://lists.racket-lang.org/users


Posted on the users mailing list.