matt
matt

Reputation: 2049

Haskell: padding out elements of a list

I have a list: ["1", "111", "11111", "1111111"] and I would like to pad out each element with underscores to a length of 11 with the the original element in the middle i.e. ["_____1_____","____111____","___11111___","__1111111__"]

I am using:

pad' x = s ++ x ++ s
  where 
    s = replicate ((11 - length x) `div` 2 ) '_'

is there a tidier/more efficient way to do this?

NB the required width will always be odd

Upvotes: 0

Views: 388

Answers (1)

Paul Johnson
Paul Johnson

Reputation: 17796

Top level declarations should always have an explicit type.

I know that you say the total number of padding underscores will always be even, but it is never a good idea to build that kind of assumption into your code. Instead you should make your functions correct under all inputs if possible. That way you don't get hidden bugs when something changes and your assumption is no longer correct.

You should also make the padded width a parameter for the same reason. You can always create a specialized version as well.

Putting these things together, an improved version would be:

pad' :: Int -> String -> String
pad' n x = replicate s1 '_' ++ x ++ replicate s2 '_'
  where 
    len = length x
    s1 = (n - len) `div` 2
    s2 = n - s1 - len

pad11 :: String -> String
pad11 = pad' 11

Upvotes: 2

Related Questions