statefulSplit

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
-- | Performs a split with some memory
statefulSplit :: (b -> a -> (a, Bool)) -> a -> [b] -> [[b]]
statefulSplit f initMem list =
    let (mem', word, rest) = consumeOne initMem list
    in word:if null rest then [] else statefulSplit f mem' rest

  where consumeOne mem [] = (mem, [], [])
        consumeOne mem (x:xs) =
            let (mem', splits) = f x mem
            in if splits then (mem', [], xs)
                         else let (mem'', word, rest) = consumeOne mem' xs
                              in (mem'', x:word, rest)


-- In that case, "memory" need only be the last processed character
splitUnixEOL = statefulSplit (\c last -> (c, c == '\n' && last /= '\r')) '0' -- anything but '\r'