HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Splitting a list into overlapping sub-lists

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
intosubsplittingoverlappinglistslist

Problem

I'm very new to Haskell. I did try it for a few days, a few years ago... but other than that, this is my second day. I'm equally unused to functional programming, by the way.

After much trial and error, I managed to write this function:

chunk :: Int -> [a] -> [[a]]
chunk n xs = chunk' n [] xs
    where
    chunk' _ results [] = results
    chunk' n results xs
        | length xs >= n = chunk' n (results ++ [take n xs]) $ tail xs
        | otherwise = chunk' n results []


This creates a list of all possible length n sub-lists, like so:

*Main> chunk 3 [1..7]
[[1,2,3],[2,3,4],[3,4,5],[4,5,6],[5,6,7]]
*Main> chunk 5 [1..7]
[[1,2,3,4,5],[2,3,4,5,6],[3,4,5,6,7]]


How can this be improved (in readability, performance, brevity etc.)?

Solution

Using ++ to concatenate lists is a bad idea for performance, and it's a sign that you are not using recursion smartly.

Here's what I came up with:

chunk :: Int -> [a] -> [[a]]
chunk n xs =  
  if   length chunk' < n then []
  else (chunk' : chunk n (tail xs))
    where chunk' = take n xs

Code Snippets

chunk :: Int -> [a] -> [[a]]
chunk n xs =  
  if   length chunk' < n then []
  else (chunk' : chunk n (tail xs))
    where chunk' = take n xs

Context

StackExchange Code Review Q#54102, answer score: 4

Revisions (0)

No revisions yet.