2010-02-27 69 views
2

我很好奇,是否有可能在Haskell中动态构建列表理解。动态构建Haskell中的列表理解

举个例子,如果我有以下几点:

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

我得到我所追求的

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

不过,我真的很想对有类似

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

这样我就可以支持N对无参数的参数N版本的all_pows。我对Haskell仍然很陌生,所以我可能忽略了一些明显的东西。这甚至有可能吗?

回答

11

名单单子的魔力:

 
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] 

这可能值得进一步的解释。

你可以写你自己的

cartesianProduct :: [[a]] -> [[a]] 
cartesianProduct [] = [[]] 
cartesianProduct (list:lists) 
    = [ (x:xs) | x <- list, xs <- cartesianProduct lists ] 

这样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]]。但是,comprehensionsmonads故意相似。标准Prelude有sequence :: Monad m => [m a] -> m [a],当m是列表monad []时,它实际上就是我们上面写的。

作为另一种捷径,mapM :: Monad m => (a -> m b) -> [a] -> m [b]仅仅是sequencemap的组合。

对于每个基地的不同权力的每个内部列表,您希望将它们乘以一个单一的数字。你可以写这个递归

product list = product' 1 list 
    where product' accum [] = accum 
     product' accum (x:xs) 
      = let accum' = accum * x 
      in accum' `seq` product' accum' xs 

或使用折叠

import Data.List 
product list = foldl' (*) 1 list 

但实际上,product :: Num a => [a] -> a已经被定义!我喜欢这种语言☺☺☺

+0

'让权力(a,b)= [a^n | n < - [0 .. b-1]]' – Tordek 2010-02-27 21:42:09

+0

@Tordek谢谢,我原汁原味了一下。 – ephemient 2010-02-27 22:30:00

+0

美丽,谢谢。 – ezpz 2010-02-27 22:48:20