[Haskell-cafe] split string into n parts

jim burton jim at sdf-eu.org
Mon Oct 23 16:51:31 EDT 2006




Jón Fairbairn-2 wrote:
> 
> 
> At a quick glance I can't see which bit needs it. The only
> mention of five is where it asks to split the string into
> groups of five characters (not into five equal parts),
> padded with Xs.
> 
Oh dear, you're right. Sorry, I read in a rush. Thanks for the solution too.


Jón Fairbairn-2 wrote:
> 
> You can do that like this:
> 
>    splitAtMb n l = let p = splitAt n l
>                    in if null $ fst p
>                       then Nothing
>                       else Just p
> 
>    in_fives l = unfoldr (splitAtMb 5)
>                         (l ++ replicate (length l `mod` 5) 'X')
> 
> To break a string into five equal parts with the last padded
> with Xs, try this:
> 
>    fifths l = let len = length l
>                   part_length = (len+4)`div`5
>                   pad_length = 5*part_length - len
>               in unfoldr (splitAtMb part_length)
>                          (l ++ replicate pad_length 'X')
> 
> I haven't checked these at all carefully, but at least they
> illustrate the use of unfoldr.  [aside: One might argue that
> the prelude ought to provide splitAtMb rather than splitAt.]
> 
> -- 
> Jón Fairbairn                                 Jon.Fairbairn at cl.cam.ac.uk
> 
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
> 
> 

-- 
View this message in context: http://www.nabble.com/split-string-into-n-parts-tf2496941.html#a6961825
Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com.



More information about the Haskell-Cafe mailing list