How to generate all possible matrices given a number n in Haskell

63 views Asked by At

I want to generate a list given a number n which returns all possible combinations from one to n recursively and without imports.

For example

generate 3 

should return:

[[1,1,1],[1,1,2],[1,1,3],[1,2,1],[1,2,2],[1,2,3],[1,3,1],[1,3,2],[1,3,3],[2,1,1],[2,1,2],[2,1,3],[2,2,1],[2,2,2],[2,2,3],[2,3,1],[2,3,2],[2,3,3],[3,1,1],[3,1,2],[3,1,3],[3,2,1],[3,2,2],[3,2,3],[3,3,1],[3,3,2],[3,3,3]]

Logically something like this, which obviously returns an error:

generate n = [replicate n _ | _ <- [1..n]]
2

There are 2 answers

2
willeM_ Van Onsem On

You can work with replicateM :: Int -> m a -> m [a]:

import Control.Monad(replicateM)

generate :: Int -> [[Int]]
generate = replicateM <*> enumFromTo 1

The replicateM essentially works as:

(\x1 x2 … xn -> [x1, x2, …, xn]) <$> fx <*> fx <*> … <*> fx

where we repeat fx n times. Here we use [1 .. n], so that means we pick an element from [1 .. n], then another one for [1 .. n] and so on, until we picked n elements, and then combine these.

0
Coder On

Here my solution without imports:

generate n = sequence (replicate n [1..n])