Nested cartesian product of Haskell lists

后端 未结 3 1321
梦毁少年i
梦毁少年i 2021-02-06 02:03

I would like to make a method where I could give it a list of lengths and it would return all combinations of cartesian coordinates up to those lengths. Easier to explain with a

3条回答
  •  你的背包
    2021-02-06 02:58

    This can be solved recursively. First, the Cartesian product of nothing is {∅}:

    cart [] = [[]]
    

    (Or define just the 1-element form if the empty product is invalid:

    cart [x] = [[i] | i <- [0 .. x-1]]
    

    )

    Then, the Cartesian product of x:xs can be written as

    cart (x:xs) = [i:rest | i <- [0 .. x-1], rest <- cart xs]
    

    In general, if you what to write a function f that requires the list's length N, try to think of a way to make f(N) depends on smaller lists e.g. f(N - 1) only, then solve the base case f(0) or f(1) etc. This transforms the problem into a recursion that can be easily solved.

提交回复
热议问题