[Haskell-cafe] split string into n parts

jim burton jim at sdf-eu.org
Mon Oct 23 15:29:07 EDT 2006

I want to split a string into 5 parts of equal length, with the last fifth
padded if necessary, but can't get it right - here's what I've got - 

> fifths :: String -> String
> fifths s = fifths' "" 0 s
>     where l = (length s) `div` 5
>               fifths' xs c []     = xs ++ (replicate (l-c) 'X')
>               fifths' xs c (y:ys) = if c == l 
>                                             then fifths' (xs++[' ',y]) 0
> ys 
>                                             else fifths' (xs++[y]) (c+1)
> ys 

which, apart from surely being uglier than need be, doesn't work:

*Main> fifths "12345"
"1 23 45"

Any thoughts? Thanks! This isn't homework BTW, I'm having a go at the ruby
quiz puzzles in haskell, which seems to be a nice way to learn.
View this message in context: http://www.nabble.com/split-string-into-n-parts-tf2496941.html#a6960346
Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com.

More information about the Haskell-Cafe mailing list