返回列表[0,[x1],[x1,x2],[x1,x2,x3] ...]的函数,其中[x1,x2,x3 ....]是原始列表

时间:2014-05-23 12:56:38

标签: haskell

如何在Haskell中创建一个获取列表并以这种方式返回列表列表的函数:

[x1,x2,x3,x4,x5....]

it should return :

[[0],[x1],[x1,x2],[x1,x2,x3],[x1,x2,x3,x4][x1,x2,x3,x4,x5]....]

没有使用在Haskell中执行此操作的就绪函数。

3 个答案:

答案 0 :(得分:2)

我假设你的意思是开头的空列表[],而不是[0]

在这种情况下,它只是inits

如果您想自己编写,请参阅以下内容:

inits xs =  [] : case xs of []      -> []
                            x : xs' -> map (x :) (inits xs')

答案 1 :(得分:0)

代码:

    import System.IO 

    transform :: [Int] -> [[Int]] 
    transform list = trans 0  
            where trans n = case (length list) >= n of 
                            True -> (take n list):( trans (n+1) ) 
                            False -> [] 
    main = do 
            print . show $ transform [1..7] 

输出:

$> ./transform
"[[],[1],[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5],[1,2,3,4,5,6],[1,2,3,4,5,6,7]]"

编辑:使用无限列表

    transform :: [a] -> [[a]]                                                    
    transform list = trans 0 []                                                  
            where                                                                
            trans :: a ->  [a]  -> [[a]]                                         
            trans n last = case last == list of                                  
                            False -> [take n list]++(trans (n+1) $ take n list)  
                            True -> []

答案 2 :(得分:0)

假设你想在开始时使用空列表:

prefixes :: [a] -> [[a]]
prefixes ls = map (\x -> take x ls) [0..(length ls)]