[Haskell-cafe] split string into n parts

Paul Brown paulrbrown+haskell-cafe at gmail.com
Mon Oct 23 15:59:33 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
> [... snip ...]
> 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.

Cool idea!  Can you post a link for the puzzles?

As for this one, don't you want the first multiple of five larger than
the length of the string?  You should be able to make things simpler
if you auto-pad the string from the get-go (forgive any syntax errors,
as I'm just composing in a browser here...):

prepad :: Integer -> String -> String
prepad n s | (length s) `mod` n == 0 = s
prepad n s = prepad n (s ++ ' ')

And now you can be sneaky:

nths :: Integer -> String -> String
nths n s = [first_nth n s] ++ nths (n-1) (after_first_nth n s)
nths 1 s = s

Where first takes the first n chars (e.g., take ((length s) `div` n))
and after_first_nth returns the tail of the list..

--
paulrbrown at gmail.com
http://mult.ifario.us/


-- 
paulrbrown at gmail.com
http://mult.ifario.us/


More information about the Haskell-Cafe mailing list