[Haskell-beginners] set multiplication

Jacek Dudek jzdudek at gmail.com
Mon Apr 14 17:53:40 UTC 2014


Well it looks I was beat to the answer by Mariano, but here's my
solution anyway. It's a little more expository, hope that helps. Note
that we both decided to use a right fold in our solutions.

{-
Define a binary operation. Note the type signature.
When used in the fold operation below, the 2nd argument
denotes the set product of the first couple of lists
(counting from the right-hand side) that were in your
initial list.
-}
f :: [a] -> [[a]] -> [[a]]
f [] _ = []
f (x : xs) yss = map (x :) yss ++ f xs yss

{-
Now for the product, we use a right fold operation to get
the product of the first two lists (counting from the right),
then distribute the elements of the next list over the result,
then the elements of the next list, and so on.
-}
setProd :: [[a]] -> [[a]]
setProd [] = []
setProd xss = foldr f (map (: []) (last xss)) (init xss)

test = [[1,2,3],[4,5],[6,7]]

On 4/8/14, Christian Maeder <Christian.Maeder at dfki.de> wrote:
> Some time ago I discovered that the monadic "sequence" function operates
> quite interestingly on lists. I don't know why you call it
> multiplication. I was looking for something like combinations:
>
> Prelude> sequence [[1,2,3], [4,5], [6,7]]
>
> HTH Christian
>
> Am 08.04.2014 07:00, schrieb Nishant:
>>
>> hi,
>>
>> I am trying to implement a set multiplication program in haskell.
>>
>> Input : [1,2,3]   [4,5]  [6,7]
>> Ouput : [ [1,4,6] , [1,4,7] , [1,5,6] , [1,5,7] ...]
>>
>>
>> I implemented it for constant number of inputs like
>>
>> setMul xs ys zs =  [ [x] ++ [y] ++ [z] |  x <- xs , y<-ys ,z <- zs]
>>
>> I am not able to generalize this for any number of lists.
>>
>> type signature would be :
>>
>> setMulMany :: [[a]] -> [[a]]
>>
>> Example :
>>
>> Input : [ [1,2,3] , [4,5] , [6,7]]
>> Ouput :  [ [1,4,6] , [1,4,7] , [1,5,6] , [1,5,7] ...]
>>
>>
>> Regards.
>> Nishant
>>
>>
>> _______________________________________________
>> Beginners mailing list
>> Beginners at haskell.org
>> http://www.haskell.org/mailman/listinfo/beginners
>>
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>


More information about the Beginners mailing list