views:

161

answers:

1

I am curious if it is possible to dynamically build a list comprehension in Haskell.

As an example, if I have the following:

all_pows (a,a') (b,b') = [ a^y * b^z | y <- take a' [0..], z <- take b' [0..] ]

I get what I am after

*Main> List.sort $ all_pows (2,3) (5,3)
[1,2,4,5,10,20,25,50,100]

However, what I'd really like is to have something like

all_pows [(Int,Int)] -> [Integer]

So that I can support N pairs of arguments without building N versions of all_pows. I'm still pretty new to Haskell so I may have overlooked something obvious. Is this even possible?

+9  A: 

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 ☺☺☺

ephemient
`let powers (a, b) = [a ^ n | n <- [0 .. b-1]]`
Tordek
@Tordek Thanks, I skimmed over the original a bit too quickly.
ephemient
Beautiful, thank you.
ezpz