Nested cartesian product of Haskell lists

后端 未结 3 1318
梦毁少年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:41

    I bet your procedural solution would involve recursion. Our Haskell solution will involve recursion too.

    So, recursion. First the recursive case.

    cart (c : cs) = [i : r | i <- [0 .. c-1], r <- rcart]
      where rcart = cart cs
    

    Here we're just saying that for each possible initial co-ordinate, and each possible combination of cartesian co-ordinates from the remaining lengths, we do the obvious thing of combining the co-ordinate with the remaining co-ordinates.

    Then the base case.

    cart [] = [[]]
    

    You might think cart [] = []. I did at first. But think about what the recursive case requires from the base case.

提交回复
热议问题