Calculate n-ary Cartesian Product

后端 未结 6 2126
别跟我提以往
别跟我提以往 2020-12-16 18:03

Given two lists, I can produce a list of all permutations the Cartesian Product of these two lists:

permute :: [a] -> [a] -> [[a]]
per         


        
6条回答
  •  無奈伤痛
    2020-12-16 18:26

    I found Eric Lippert's article on computing Cartesian product with LINQ quite helpful in improving my understanding of what was going on. Here's a more-or-less direct translation:

    cartesianProduct :: [[a]] -> [[a]]
    cartesianProduct sequences = foldr aggregator [[]] sequences
                       where aggregator sequence accumulator = 
                             [ item:accseq |item <- sequence, accseq <- accumulator ]
    

    Or with more "Haskell-y" terse, meaningless parameter names ;)

    cartesianProduct = foldr f [[]]
                        where f l a = [ x:xs | x <- l, xs <- a ]
    

    This winds up being quite similar to sclv posted after all.

提交回复
热议问题