[Haskell-cafe] a sort of chunk

PICCA Frederic-Emmanuel frederic-emmanuel.picca at synchrotron-soleil.fr
Sun Jan 19 11:17:54 UTC 2020


Hello viktor

import           Data.List

data T = T String Int Int
  deriving Show

l :: [T]
l = [ T "1" 0 30
    , T "2" 0 40
    ]

tweight :: T -> Int
tweight (T n f t) = t - f

chunks :: Int -> (a -> Int) -> [a] -> [[a]]
chunks target weight xs = go 0 xs
  where
    go _ [] = []
    go n (h:ts)
      | null ts                          = [h] : []
      | let w = n + weight h, w < target = cons1 h $ go w ts
      | otherwise                        = [h] : go 0 ts
    cons1 h ~(a:b) = (h : a) : b


main :: IO ()
main = do
  let cs = chunks 10 tweight l
  print cs

seems to work, but this is not what I want :))

picca at cush:~$ runhaskell test.hs
[[T "1" 0 30],[T "2" 0 40]]

I want at the end to split each of my T into  chunk of length target.

like this

[[T "1" 0 10], [T "1" 10 20], [T "1" 20 30], [T "2" 0 10], ...]

So a split function like this should be used

split :: Int -> a -> (a, a)
split s (T n f t) = (T n f s, T n s t)


Cheers

Frederic


More information about the Haskell-Cafe mailing list