Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: cartesian product of a list with itself n times

Tags:

haskell

What's a simple way of computing the cartesian product of a list with itself n times?

That is, how can I define the function cartesianExp :: Int -> [a] -> [[a]].

For instance, the cartesian product of [1,2] with itself 3 times (n = 3) should be:

[
 [1, 1, 1],
 [1, 1, 2],
 [1, 2, 1],
 [1, 2, 2],
 [2, 1, 1],
 [2, 1, 2],
 [2, 2, 1],
 [2, 2, 2]
]
like image 952
Anakhand Avatar asked Dec 11 '25 21:12

Anakhand


1 Answers

You can work with replicateM :: Applicative f => Int -> f a -> f [a] to do this. Indeed:

ghci> import Control.Monad(replicateM)
ghci> replicateM 0 "abc"
[""]
ghci> replicateM 1 "abc"
["a","b","c"]
ghci> replicateM 2 "abc"
["aa","ab","ac","ba","bb","bc","ca","cb","cc"]
ghci> replicateM 3 "abc"
["aaa","aab","aac","aba","abb","abc","aca","acb","acc","baa","bab","bac","bba","bbb","bbc","bca","bcb","bcc","caa","cab","cac","cba","cbb","cbc","cca","ccb","ccc"]
ghci> replicateM 3 [1,2]
[[1,1,1],[1,1,2],[1,2,1],[1,2,2],[2,1,1],[2,1,2],[2,2,1],[2,2,2]]
like image 61
Willem Van Onsem Avatar answered Dec 13 '25 10:12

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!