Nested cartesian product of Haskell lists

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

    Umm..

    cart = sequence . map (enumFromTo 0 . subtract 1)
    

    It's reasonable to expect that a [[a]] -> [[a]] function doing what we expect already exists in the library. So if one is not familiar with sequence, finding it is a simple matter of hoogling it.

    Edit: as newacct pointed out:

    cart = mapM (enumFromTo 0 . subtract 1)
    

    This can also be found by feeding the previous solution to HLint.

提交回复
热议问题