The magic of the list monad:
ghci> let powers (a, b) = [a ^ n | n <- [0 .. b-1]]
ghci> powers (2, 3)
[1,2,4]
ghci> map powers [(2, 3), (5, 3)]
[[1,2,4],[1,5,25]]
ghci> sequence it
[[1,1],[1,5],[1,25],[2,1],[2,5],[2,25],[4,1],[4,5],[4,25]]
ghci> mapM powers [(2, 3), (5, 3)]
[[1,1],[1,5],[1,25],[2,1],[2,5],[2,25],[4,1],[4,5],[4,25]]
ghci> map product it
[1,5,25,2,10,50,4,20,100]
ghci> let allPowers list = map product $ mapM powers list
ghci> allPowers [(2, 3), (5, 3)]
[1,5,25,2,10,50,4,20,100]
This probably deserves a bit more explanation.
You could have written your own
cartesianProduct :: [[a]] -> [[a]]
cartesianProduct [] = [[]]
cartesianProduct (list:lists)
= [ (x:xs) | x <- list, xs <- cartesianProduct lists ]
such that cartesianProduct [[1],[2,3],[4,5,6]]
⇒ [[1,2,4],[1,2,5],[1,2,6],[1,3,4],[1,3,5],[1,3,6]]
.
However, comprehensions and monads are intentionally similar. The standard Prelude has sequence :: Monad m => [m a] -> m [a]
, and when m
is the list monad []
, it actually does exactly what we wrote above.
As another shortcut, mapM :: Monad m => (a -> m b) -> [a] -> m [b]
is simply a composition of sequence
and map
.
For each inner list of varying powers of each base, you want to multiply them to a single number. You could write this recursively
product list = product' 1 list
where product' accum [] = accum
product' accum (x:xs)
= let accum' = accum * x
in accum' `seq` product' accum' xs
or using a fold
import Data.List
product list = foldl' (*) 1 list
but actually, product :: Num a => [a] -> a
is already defined! I love this language ☺☺☺