简体   繁体   English

使用Haskell在元组中以长度为2 ^ 0,2 ^ 1,…,2 ^ N的列表分割列表

[英]Split list in tuple with lists of length 2^0, 2^1, … , 2^N using Haskell

I'm trying to solve Haskell problem, but I don't have any clue where to start. 我正在尝试解决Haskell问题,但是我不知道从哪里开始。 I need to split list in lists with length of 2^0, 2^1, 2^3 .. elements. 我需要将列表拆分成长度为2 ^ 0、2 ^ 1、2 ^ 3 ..个元素的列表。 So if we have list [1,2,3,4,5,6,7,8,9,10,11,12,13] after using our function we should have result [[1],[2,3],[4,5,6,7],[8,9,10,11,12,13]] 因此,如果在使用函数后获得列表[1,2,3,4,5,6,7,8,9,10,11,12,13] ,我们应该得到结果[[1],[2,3],[4,5,6,7],[8,9,10,11,12,13]]

You can use the function: splitAt :: Int -> [a] -> ([a],[a]) , and then use recursion: 您可以使用以下函数: splitAt :: Int -> [a] -> ([a],[a]) ,然后使用递归:

blocks :: Int -> [a] -> [[a]]
blocks _ [] = []
blocks n ls = la : blocks (2*n) lb
    where ~(la,lb) = splitAt n ls

So in the case we have a blocks 1 [1,2,3,4,5,6] we will obtain [[1],[2,3],[4,5,6]] . 因此,在我们有一个blocks 1 [1,2,3,4,5,6]的情况下,我们将获得[[1],[2,3],[4,5,6]] In the first case, we look if the list we give to blocks is empty, in which case, there is nothing to split, so we return the empty list. 在第一种情况下,我们查看提供给块的列表是否为空,在这种情况下,没有要分割的内容,因此我们返回空列表。 In the recursive case, we splitAt the ls list into la and lb . 在递归的情况下,我们splitAtls列表到lalb The la is our first list, and the lb we need to split further. la是我们的第一个列表,而lb我们需要进一步lb列表。 We do the recursion with n*2 as new split length to ensure that the length of the lists will increase like powers of two. 我们使用n*2作为新的分割长度进行递归,以确保列表的长度将像2的幂一样增加。

Maybe you can also use zip and groupBy . 也许您也可以使用zipgroupBy Seems to be working, but is not so straightforward. 似乎正在工作,但不是那么简单。

import Data.List
a="Hello World!"
p=[2^n| n<-[0..]]
pa=take (length a) p
b=[elem n pa| n<-[1..length a]]
c=zip a b
d=groupBy (\x y->snd y==False) c
e=map (map (\x->fst x)) d

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM