{-| Module : FiniteCategories Description : Simple functions to compute cartesian products of finite lists. Copyright : Guillaume Sabbagh 2021 License : GPL-3 Maintainer : guillaumesabbagh@protonmail.com Stability : experimental Portability : portable Simple functions to compute cartesian products of finite lists. -} module Utils.CartesianProduct ( cartesianProduct, cartesianPower, (|*|), (|^|) ) where import Data.List (replicate) -- | Returns the cartesian product of the finite lists. -- -- cartesianProduct [A,B,C,...] = A x B x C x ... cartesianProduct :: [[a]] -> [[a]] cartesianProduct [] = [[]] cartesianProduct (x:xs) = concat ((\l -> [e:l | e <- x]) <$> (cartesianProduct xs)) -- | Returns the cartesian product of two lists (|*|) :: [a] -> [a] -> [[a]] x |*| y = cartesianProduct [x,y] -- | Returns the cartesian product of a list by itself /k/ times. cartesianPower :: [a] -> Int -> [[a]] cartesianPower l k = cartesianProduct $ replicate k l -- | Infix alias for `cartesianPower` (|^|) = cartesianPower