[Haskell-beginners] Custom partition lists into groups by providing group sizes using foldl

Apoorv Ingle apoorv.ingle at gmail.com
Tue Jul 11 21:26:04 UTC 2017


Hi,

I am trying to write a partition function where we pass group sizes and the list we want to partition into groups 
as arguments and get back a list of groups (or list of lists in this case). My first attempt was by using an auxiliary inner function

{-# LANGUAGE ScopedTypeVariables #-}

module Partition where

partition :: [Int] -> [a] -> [[a]]
partition ds ps = reverse $ paux ds ps []
  where
    paux :: [Int] -> [a] -> [[a]] -> [[a]]
    paux []         []   ps' = ps'
    paux []         ps ps' = [ps] ++ ps’ 
    paux _         []   ps' = ps'
    paux (d:ds') ps ps' = paux ds' (snd (splitAt d ps)) ([fst (splitAt d ps)] ++ ps')

——————

*Partition> partition [2, 3] [1,2,3,4,5]
[[1,2],[3,4,5]]
*Partition> partition [1, 2] [1,2,3,4,5]
[[1],[2,3],[4,5]]
*Partition> partition [1, 2, 5] [1,2,3,4,5]
[[1],[2,3],[4,5]]


I was speculating if we could write the same function using foldl function but haven’t been able to figure it out.
I would really appreciate if you can give me pointers on how we can implement it.

partition' :: [Int] -> [a] -> [[a]]
partition' [] ds = [ds]
partition' ps ds = foldl ??? ???' ???''

contrary to my speculation is it even possible to write such a function using foldl if so why not?

Regards,
Apoorv Ingle
Graduate Student, Computer Science
apoorv.ingle at ku.edu <mailto:apoorv.ingle at ku.edu>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20170711/ef9d12db/attachment.html>


More information about the Beginners mailing list